Trying to Call a Function From Tagged Objects

Hi there,

I try not to ask questions and use Google as much as possible, but I am completely stuck.

I am trying to run a script which upon a GUI button click, calls a function from all objects in the scene with a specific tag. All of these objects will have the same script on them. Here is my code, but I just can’t seem to get it right.

using UnityEngine;
using System.Collections;


public class TheGUI : MonoBehaviour {

	public Detonator derpy;

	void OnGUI () {

		Detonator derpy = GameObject.FindGameObjectsWithTag ("Bombs");

		// Make a background box
		GUI.Box(new Rect(10,10,100,90), "Loader Menu");
		
		// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
		if(GUI.Button(new Rect(20,40,80,20), "Esplode")) {
			derpy.Explode();
		}
	}
}

Thanks in advance!!!

You guys are always so helpful.

GameObject.FindGameObjectsWithTag will return an array of all the game objects found with that tag. So you need to store that into an array and not a single variable.

So if you want to explode all the game objects after the button click the code should be:

public class TheGUI : MonoBehaviour {

GameObject[] bombs;

    void Start()
    {
        bombs = GameObject.FindGameObjectsWithTag ("Bombs");
    }

    void OnGUI () {
 
        // Make a background box
        GUI.Box(new Rect(10,10,100,90), "Loader Menu");
 
        // Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
        if(GUI.Button(new Rect(20,40,80,20), "Esplode")) {
             for(int i=0; i<bombs.Length; i++)
             {
                 bombs*.GetComponent<Detonator>().Explode();*

}
}
}
}

FindGameObjectsWithTag() returns an array of game objects. So you would do something like this:

    if(GUI.Button(new Rect(20,40,80,20), "Esplode")) {
        GameObject[] objs = GameObject.FindGameObjectsWithTag ("Bombs");
        foreach (GameObject go in objs) {
            Detonator derpy = go.GetComponent<Detonator>();
            if (derpy != null) {
                 derpy.Explode();
             }
        }
    }