Spawn random items, in an array

Hello im trying to spawn a random item in a selected position. Im having trubble tho, This is my script it spawns objects at a random position in the world. And suppose to choose from a random object to spawn, but it doesnt work. Any help is appreciated!

using UnityEngine;
using System.Collections;

public class SpawnItemsAtRandomPos : MonoBehaviour {
	
	public GameObject Item_1;
	public GameObject Item_2;
	public GameObject Item_3;
	public int z;
	public int x;
	public int SpawnTimer = 50;
	
	// Use this for initialization
	void Start ()
	{
		while (SpawnTimer > 0)
		{
			int z = Random.Range (-1000, 1000);
			int x = Random.Range (-1000, 1000);
			int y = 0;
			Vector3 blockPos = new Vector3(x,y,z);
			GameObject Item;

			if(Random.Range(1, 3) == 1)
			{
				Item = Item_1;
			}

			if(Random.Range(1, 3) == 2)
			{
				Item = Item_2;
			}

			if(Random.Range(1, 3) == 3)
			{
				Item = Item_3;
			}

			Instantiate(Item, blockPos, Quaternion.identity);
			SpawnTimer--;
		}
	}
}

Hi there @carlqwe

Are you receiving any errors in the console? If not, you should be and they’ll tell you what’s going wrong.

If you look within your while loop you’ll notice that you have declared a local variable named “Item” and it’s currently unassigned.

GameObject Item;

You only assign a value to this variable if one of the following conditionals is true.

             if(Random.Range(1, 3) == 1)
             {
                 Item = Item_1;
             }
 
             if(Random.Range(1, 3) == 2)
             {
                 Item = Item_2;
             }
 
             if(Random.Range(1, 3) == 3)
             {
                 Item = Item_3;
             }

But, later on, you instantiate an object using this variable.

Instantiate(Item, blockPos, Quaternion.identity);

Now, whilst you know that one of the following conditions will become true, Unity cannot guarantee this and so, to stop itself from instantiating an unassigned variable it should throw a compiler error along the lines of:

“Use of unassigned local variable”

To fix this, simply place the instantiate call within the conditionals and your problem should be solved.

			if(Random.Range(1, 3) == 1)
			{
				Item = Item_1;
				Instantiate(Item, blockPos, Quaternion.identity);
			}

			if(Random.Range(1, 3) == 2)
			{
				Item = Item_2;
				Instantiate(Item, blockPos, Quaternion.identity);
			}

			if(Random.Range(1, 3) == 3)
			{
				Item = Item_3;
				Instantiate(Item, blockPos, Quaternion.identity);
			}

I hope this helps! :slight_smile: