Accessing UI elements in code
All the UI elements can be accessed and manipulated in code like other GameObjects. To access a UI element in code, you must include the UnityEngine.UI
namespace and the correct variable type. Let’s look at the UnityEngine.UI
namespace.
UnityEngine.UI namespace
A namespace is a collection of classes. When you include a namespace in your class, you are stating that you want to access all the variables and methods (functions) in your class. Namespaces are accessed at the top of a script with the using
keyword.
By default, all new C# scripts include the System.Collections
, System.Collections.Generic
and UnityEngine
namespaces. To access the properties of UI elements via code, you must first use the UnityEngine.UI
namespace.
Therefore, at the top of your C# script, you will need to include the following line to signify that you want to use the UnityEngine.UI
namespace:
using UnityEngine.UI;
Without using the namespace, any variable...