How do you find a GameObject that is attached to the script using a string?

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);

obj.gameObject.SetActive(true);
other.gameObject.SetActive(true);

This isn’t the exact code, it’s just an example to explain what I’m trying to do? I hope it makes sense.

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.

To find game object by name, you need to use:

However, that will only find active game objects so this won’t work if your purpose is to find an inactive game object and then activate it.

Instead, put those game objects in a dictionary where the key is your “object number” (in Start):

Dictionary<string, GameObject> myGameObjects = new Dictionary<string, GameObject>();
myGameObjects.Add(“A1”, ObjA1);
etc…

Then to find find and activate it:

myGameObjects[objNumber].SetActive(true);

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.

GameObject.Name using find is a horrible idea. Better use a List of GameObject and then query it with go.name == “thisname”