- Home /
Calling Method of A GameObject's Script
I have a List of GameObjects. All these GameObjects are of prefab. This prefab has a script. Is it possible to cast the GameObjects in the List to this prefab and then call a method in the prefab's script? Is there a better way to do this? Thanks in advanced. Here is my pseudocode.
public class EngineScript
{
public gameObject prefabObject;
List<GameObject> listOfPrefabObjects;
void doStufff()
{
foreach(GameObject objectFoo in listOfPrefabObjects)
{
//how to call doFunStuff?
}
}
}
public class prefabScript //prefab has this
{
public void doFunStuff()
{
//stuff done
}
}
Answer by Cherno · May 17, 2015 at 10:21 PM
foreach(GameObject objectFoo in listOfPrefabObjects)
{
objectFoo .Getcomponent<prefabScript>().doFunStuff();
}
et voila :]
Thanks, it worked. Except that it is "GetComponent" ins$$anonymous$$d of "Getcomponent". :)
If all your prefabs have this prefabScript attached, you can declare your "listOfPrefabObjects" like this:
List<prefabScript> listOfPrefabObjects;
Since all your prefabs have this script attached you can still drag and drop them in the inspector into that list. The great advantage is that you don't have to use GetComponent. Also when you instantiate the prefab from that reference, Instantiate will return the prefabScript reference of the instantiated prefab:
foreach(prefabScript foo in listOfPrefabObjects)
{
foo.doFunStuff();
}
// ........
prefabScript instance = (prefabScript)Instantiate(listOfPrefabObjects[0]);