New to C#.. Simple issue??

Hi,
I am trying to randomly instantiate one of three objects by using the following variables and method…

public GameObject[] randomSprayObject;
	public GameObject healthSprayObject;
	public GameObject firepowerSprayObject;
	public GameObject speedSprayObject;
	public GameObject sprayObject;
	
	private bool _delayedExplosionStarted = false;
	private float _explodeDelay;
	
	public void specifyRandomBox(){

		// select random number 0, 1 or 2.
		int sprayNumber = Random.Range(0, 3);
		if (sprayNumber == 0) {
			// if 0 set chosenRandomBox to healthbox.
			sprayObject = healthSprayObject;
			print("hello0");
		}
		else if (sprayNumber == 1) {
			// if 1 set chosenRandomBox to firepowerbox.
			sprayObject = firepowerSprayObject;
			print("hello1");
		}
		else if (sprayNumber == 2) {
			// if 2 set chosenRandomBox to speedbox.
			sprayObject = speedSprayObject;
			print("hello2");
		}
	}

The “hello-n” are to see if the random number method is working… which it is, perfectly.

My problem comes with instantiating the GameObjects. I have attatched my prefabs in the inspector to their respective variable names (healthSprayObject, firepowerSprayObject, speedSprayObject). HOWEVER, i have not attached one to “sprayObject” (assuming that it would just be assigned as one of the previously stated 3).

I then call my method before I instantiate my GameObject inside another method. I instantiate using.

GameObject chunk = Instantiate(speedSprayObject, (this.transform.position + randVec), this.transform.rotation) as GameObject;

It works fine without my added method, if I add the prefab to sprayObject in the inspector.

Does anybody know why my three GameObjects are not being assigned?

Thanks,
Tarsus

You could simplify that a lot by using an array, which you already seem to have a variable for anyway.

	public GameObject[] randomSprayObject;
	
	public void SpecifyRandomBox() {
		GameObject chunk = Instantiate(randomSprayObject[Random.Range(0, randomSprayObject.Length)],
					       transform.position + randVec,
					       transform.rotation) as GameObject;
	}

–Eric

No need for as anymore.

http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.ltTgt.html