0
\$\begingroup\$

Why does the following code not work?

I want to instantiate prefabs in a list and then use it as a GameObject like that :

public GameObject prefab;

void Start()
{

 ArrayList players = new ArrayList();

  for(int i=0; i<5; i++)
  {
        players.Add( (GameObject)Instantiate(prefab));
  }

  players[2].transform.position = new Vector3(1, 1, 1);

}

there is an error message

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Also, and I'm not totally sure, but, if your list is only in the Start method, most likely the game objects will be removed at the end of the scope. \$\endgroup\$ – Vaillancourt Nov 26 at 18:49
2
\$\begingroup\$

I'm not super familiar with Unity and c#, but...

The ArrayList class is designed to hold heterogeneous collections of objects. (Source)

So the only thing your players contains, is objects (at least w.r.t. the world).

You either want to cast the content before using it:

((GameObject)players[2]).transform.position = ...

Or use a clearer type like List<GameObject>, which will explicitly tell the world that it contains GameObjects, and let you do what you want.

\$\endgroup\$
1
\$\begingroup\$

I think your code is not working because you are adding prefabs to another list(numbers) Your code should be like this

void Start()
{

 ArrayList players = new ArrayList();

  for(int i=0; i<5; i++)
  {
        players.Add((GameObject)Instantiate(prefab));
  }

  players[2].transform.position = new Vector3(1, 1, 1);

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.