Hey guys. I have a small problem.
I need to GameObject.Find an inactive object, its name is stored in a string InRoom, (that I change with PlayerPrefs when player is touching a checkpoint in a new room) (Edit: I mean it will Find an object with the name that is written in the string)
So I used GameObject.Find(InRoom) to SetActive it, but it was inactive at the start and I had an exception.
Is there a way to access an inactive GameObject, finding it with a string, not using it in Inspector? And I can’t activate it before the game starts, (or I will have many bugs and my player will fall in a random direction)
Thank you!
There are a lot of ways to find arbitrary GameObjects, and GameObject.Find is basically the worst way. It’s slow, unreliable, and as you’ve discovered, can’t find inactive GameObjects. If you accidentally share a name between two objects that’ll break it too, even if one of them is in a completely different place (such as the UI).
For your situation, I think you should have a manager object where you assign links to every object that may be activated with this system. It’d be much faster and more reliable. It would look something like:
public GameObject[] activatableObjects;
private Dictionary<string, GameObject> activationLookup;
void Awake() {
activationLookup = new Dictionary<string, GameObject>();
for (int g=0;g<activatableObjects.Length;g++) {
activationLookup.Add(activatableObjects[g].name, activatableObjects[g]);
}
}
public GameObject Find(string findName) {
if (activationLookup.ContainsKey(findName)) return activationLookup[findName];
else return null;
}
You could put this manager on a singleton to make it as easily accessible as GameObject.Find is.
Saving a link to it in the Inspector is the best, simplest way. But since you said you didn’t want to to that, you could give it an empty always-active parent. Once you find the parent, get the child with transform.Find(“theName”). That works in inactive objects, so will find the inactive child. Or just use transform.GetChild(0).
I’d do what both the above have suggested, but another option is to leave the GameObject itself enabled, but disable all the components and children. Find would work then.
I tried transform.Find, but what do I use to enable the object if it returns Transform?
You can always get the GameObject via yourTransform.gameObject