0
\$\begingroup\$

I have three gameobject(G1,G2,G3) and I have set their tag name as "enemy".And I have another gameobject(Manager) where I have attached the script and I have a button when I click on the button the script in all the three gameobjects should be disabled .But the problem is that ,the script is disabled for only one gamobject.

public void ArrowIndicatorInvisible()
{
    GameObject.FindWithTag ("enemy").GetComponent<MessageScript>().enabled=false;
}

What will be issue.Can anybod help me solving it

\$\endgroup\$

3 Answers 3

2
\$\begingroup\$

FindWithTag returns only the first GameObject with the tag. You need to use FindGameObjectsWithTag to retrieve a list of all GameObject that are in the Scene.

More info: https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

\$\endgroup\$
4
\$\begingroup\$

It looks like you probably need FindGameObjectsWithTag, which returns an array of GameObjects rather than a single object

Once you have that you can loop over the objects like so:

public void ArrowIndicatorInvisible()
{
    GameObject[] objs = GameObject.FindGameObjectsWithTag("enemy");

    for (int i = 0; i < objs.Length; i++) {
        MessageScript m = objs[i].GetComponent<MessageScript>();
        if (m != null) {
            m.enabled = false;
        }
    }
}
\$\endgroup\$
0
2
\$\begingroup\$

you need to use GameObject.FindObjectsWithTag() store the result of this method in a array or list, then iterate over said collection and set the enable of the script for each one. Your current code returns only one active game object with the specified tag.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .