Instantiate object from list c#

I'm a beginner in programming with C#, and I'm trying Unity.

When I try to instantiate a gameObject random from an array list(list), but I have a error (The tape object cannot be used as tope parapete T. )and I don't find the solution.

I have 6 gameobjects:

public gameobject Red;
public gameobject yellow;
etc... 

to 6.

y cont have a arraylist dynamic for add or remote object. Like this:

public ArrayList list = new ArrayList();

Then, I add the gameobjects:

list.Add (Red);
list.Add(Yellow);

And to finish, I instantiate random objects from arraylist (sometimes different number of objects )

color = Instantiate(list[random.range(0, list.Length)]);

But not found, and have this error:

The tape object cannot be used as tope parapete T.

Upvotes: 0

Views: 1934

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112372

The Instantiate method is probably declared like this:

Color Instantiate(GameObject gameObject)
{
    // ...
}

But ArrayList is not strongly typed, i.e. it returns items of object type. Therefore you must cast the items to GameObject:

color = Instantiate((GameObject)list[random.range(0, list.Length)]);

But a better solution is to use a strongly typed generic list List<GameObject>. It works much like ArrayList but returns items typed as GameObject.

public List<GameObject> list = new List<GameObject>();
list.Add(Red);
list.Add(Yellow);

color = Instantiate(list[random.range(0, list.Count)]);

Upvotes: 0

user5447154
user5447154

Reputation:

It's a question about picking a random item from a list. Let me propose to use a List<T> instead of an ArrayList. Here an example:

static void Main()
{
    var Red = new GameObject();
    var Yellow = new GameObject();

    List<GameObject> gameObjects = new List<GameObject>() { Red, Yellow };
    var randomGameObject = gameObjects[(new Random()).Next(gameObjects.Count)];

    // color = Instantiate(randomGameObject)

    //Console.WriteLine(randomGameObject);
    Console.ReadLine();
}

Upvotes: 1

Related Questions