- Home /
Can't set the random position for an Instance.
Hello everyone :)
I'm trying to do my own whack-a-mole kind of game. I made an array of Vector3s with possible positions and randomising them to Debug.log works fine. I have an error though, when I try to use the random position when instantiating my prefab. Here's my code:
using UnityEngine;
using System.Collections;
public class pojawia_w_miejscu : MonoBehaviour {
public GameObject zombiePrefab;
pozycje pozycja = new pozycje();
void Update ()
{
if(Input.GetKeyDown(KeyCode.A))
{
Object zombieInstance;
zombieInstance = Instantiate(zombiePrefab, pozycja.positions[Random.Range(0, 8)]);
}
}
}
And here's an error: No overload for method 'Instantiate' takes '2' arguments Pozycje is the class that has an array storing possible positions.
accordingly positions and position in my little known language :) cheers!
Answer by vexe · Sep 14, 2013 at 04:48 PM
Just check the docs, Instantiate takes an Object, position and rotation:
static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
you're only giving the first two:
zombieInstance = Instantiate(zombiePrefab, pozycja.positions[Random.Range(0, 8)]);
So try:
zombieInstance = (GameObject) Instantiate(zombiePrefab, pozycja.positions[Random.Range(0, 8)], Quaternion.identity);
A side note: when you're dealing with arrays/lists + Random.Range, let the max range be always array.Length-1
or list.Count-1
so that you don't accidentally go beyond your array/list limit and get Index out of bounds exception.
How did it go? did my answer help you? if so, please mark it as correct :)
had to give up my machine for a moment for this: http://vimeo.com/67897675 :) it'll be back after the techno party in couple hours and I bet your answear's gonna make it happen :) thanks!
After tinkering with my random function and reading everything here http://docs.unity3d.com/Documentation/$$anonymous$$anual/InstantiatingPrefabs.html it works bonkers :)
Thanks!