I am storing the instances as Objects in a Generic List. I would like to call some functions of the prefabs from the object that keeps the List.
Is that possible?
Sure. Instantiated objects basically get everything that the prefab has. Let’s say you have a list like this: (in C#, but similar for JS)
List<Object> instances = new List<Object>();
instances.Add(Instantiate(prefab);
...
If they’re GameObjects and you want to call a GameObject method or access a property, you can cast it as a GameObject:
foreach (Object o in instances) {
GameObject go = o as GameObject;
if (go != null) {
Debug.Log("My name is " + go.name);
}
}
If you want to call a method on a component (MonoBehaviour), you can use GetComponent:
// Make everyone jump:
foreach (Object o in instances) {
GameObject go = o as GameObject;
if (go != null) {
JumpController j = go.GetComponent<JumpController>();
if (j != null) {
j.Jump();
}
}
}
Thanks for the help. I managed to get it going using this:
List<GameObject> EnemyArmy = new List<GameObject>();
void Start()
{
Transform t = (Transform)(Instantiate(enemyPrefab, new Vector3(-8.0f, -2.0f, 7.8f), Quaternion.identity) );
GameObject go = t.gameObject;
EnemyArmy.Add(go);
}
void Update ()
{
foreach (Object o in EnemyArmy) {
GameObject go = o as GameObject;
if (go != null) {
enemyBehaviorScript j = go.GetComponent<enemyBehaviorScript>();
if (j != null) {
int g = 6;
j.RunCommand(g);
}
}
}
}
Again Thanks TonyLi.