I have a script that instantiates objects. I want to be able to send information to all of these objects, every time the player uses an ability. There is a maximum of 100 objects. What is the most efficient way to do this?
Since you are instantiating the objects yourself, you can use the same class to keep track of all the created objects. What exactly it is that you use to keep track of the objects is up to you. Personally, I like List. Once you have that, you can just loop through it to send the information to all the objects.
using System.Collections.Generic;
List<GameObject> goList = new List<GameObject>();
void InstantiateAddList()
{
GameObject go = Instantiate(//...);
goList.Add(go);
}
void OnAbilityUse()
{
//Ability use stuff
foreach(GameObject go in goList)
{
go.SendInformation();
}
}
sprawww is right, but I’m gonna directly answer the original question anyway. It’s definitely NOT efficient, though. Keeping track of all gameobjects/scripts manually is the best way I figure.
YourScriptName[] yourScriptArray = FindObjectsOfType(typeof(YourScriptName)) as YourScriptName[];
foreach (YourScriptName yourScriptName in yourScriptArray ) {
yourScriptName .FunctionName();
}
If you can make all the instantiated objects childs of the same game object you can use the BroadcastMessage function: Unity - Scripting API: Component.BroadcastMessage
It will call the function with the name you want in every component that has that function, for the game object that has the script calling the function and all it’s children. I haven’t tested it, but I guess it goes through the full hierarchy of childs, not just the first level.
I don’t know if this is efficient, probably it takes more time than having a list of objects to call that function, but maybe you can trade a little speed at runtime for more speed at coding.