Unity 3D: Set the Text of Game Objects Text Component in Unity Using C#

7/27/2015 11:12:01 PM

The following C# code will get the Text component of a GameObject in Unity and set the text.

public static void Set_Text(Component component, string text)
{
	if (component != null)
	{
		Set_Text(component.gameObject, text);
	}
}
public static void Set_Text(GameObject gameObject, string text)
{
	if (gameObject != null)
	{
		var textObject = gameObject.GetComponent<UnityEngine.UI.Text>();
		if (textObject == null)
		{
			textObject = gameObject.GetComponentInChildren<UnityEngine.UI.Text>();
		}

		if (textObject != null)
		{
			textObject.text = text;
		}
	}
}