Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 2 down vote accepted

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

share|improve this answer

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;
        }
    }
}
share|improve this answer
    
thanks a lot . Its worked – user1509674 2 days ago

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.