In my use of Unity so far, I've been defining element names programmatically with classes like this:
public class MyClass : MonoBehaviour
{
public const string Name = "MyName";
public void Awake()
{
name = Name;
}
}
My hope with this is to avoid magic strings in my project. Any other object that wants this object can run GameObject.Find
with this constant and if I ever want to change the name for whatever reason, I only have to change one place and everything should just work.
public void Awake()
{
GameObject x = GameObject.Find(MyClass.Name);
}
The issue that I'm seeing is Unity sometimes failing to find the object, instead just giving me null
. I'm sure the problem is the order of different objects getting ran by Unity, but I'm not sure what the best practice would be here.
One option would be to use Awake
for naming and Start
for finding other objects, but this seems to be the opposite of what the documentation recommends for these functions. Would doing this prove to have negative consequences in the future? Is there another approach developers take to avoiding magic strings akin to this?