- Home /
Calling a function across all instances of an object
I've got a whole bunch of "tile" objects in the game (all instances of the same prefab). The prefab consists of a pretty standard transform + script + collider etc. What I want to be able to do is call the same function across all the objects at once. Is there a way to do this?
Answer by duck · Feb 07, 2012 at 04:33 PM
A simple quick way to do this would be to do a FindObjectsOfType, specifying the type as the name of your script. This will return an array of all currently active instances of that script.
You can then loop through the array and call the function on each one in turn.
FindObjectsOfType is relatively slow, so if you need a solution with more performance, either cache the result and re-use it (if your objects aren't being created and destroyed regularly), or have each script instance be responsible for adding and removing itself to/from a list, making the "Find" command unnecessary.
That's similar to what I'm doing with it now - I'm putting all the objects in a list as they are instantiated, then iterating through it calling the function. Had just wondered if there was a better way.
Answer by gabs · Feb 07, 2012 at 04:38 PM
I'd do this if I didn't have to worry about deactivating it for specific scenes etc:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class CoinToken : MonoBehaviour { protected static List<CoinToken> allTokens;
public static List<CoinToken> AllInstances
{
get
{
if(allTokens == null)
allTokens = new List<CoinToken>();
return allTokens;
}
}
protected static void AddToken(CoinToken item)
{
if(allTokens == null)
allTokens = new List<CoinToken>();
if(allTokens.Contains(item))
return;
allTokens.Add(item);
}
protected static void RemoveToken(CoinToken item)
{
if(allTokens == null)
allTokens = new List<CoinToken>();
if(!allTokens.Contains(item))
return;
allTokens.Remove(item);
}
void Awake ()
{
AddToken(this);
}
~CoinToken()
{
RemoveToken(this);
}
// dummy function to test this
public void SayHello()
{
Debug.Log(gameObject.name + " HELLO!");
}
//function to say hello to all
public static void SayHelloAll()
{
foreach(CoinToken token in AllInstances)
{
token.SayHello();
}
}
}
and to call it from another script, use: CoinToken.SayHelloAll();