I can’t figure out how to grab a GameObject that is attached to my script using a string. I feel one of the reasons for this is that I’m not wording it right.
I want to grab the GameObject using a string so I can active it, which is requiring something like this. But it’s not working and I can’t find out how to write it properly.
public GameObject ObjA1;
public GameObject ObjB2;
public GameObject ObjC3;
public GameObject OtherA1;
public GameObject OtherB2;
public GameObject OtherC3;
private string ObjNumber;
ObjNumber = “C3”;
var obj = transform.Find(“Obj” + ObjNumber);
var other = transform.Find(“Other” + ObjNumber);
I’m not entirely sure what you’re trying to do, but usually whenever find yourself using Find you should re-evaluate what you’re doing because there is probably a much better way of doing it. The Find methods are very slow and should be avoided at all costs.
I think Transform.Find works on children only, so the Transform component you’re looking for must be a child of transform on the current gameObject. Otherwise, use GameObject.Find, which will look through all game objects in the hierarchy.
Is there any other way to grab a gameobject using a string other then using find? GameObject.Find doesn’t seem to work since all my object are set inactive, which is why I’m trying to active certain ones.
Ah, that’s right. GameObject.Find doesn’t find objects that are not active. But this just goes back to my original point, there’s likely a better way to do what you want to do. Without knowing more about what you want to do it’s hard to suggest a course of action here though. What is this script and what is it trying to find? I’m sure there’s a better way to do it.
Interesting…This should work. Is it possible to grab two gameobjects at the same time doing this? Just wondering since it would help shrink the script.
No, you’d still have to use the dictionary twice to get two game objects. Don’t worry about eliminating lines of text from your script though, that’s irrelevant.