- Home /
Instatiate randomly along a vector
Hi, I'm new to Unity and I'm trying to get prefabs to only instatiate randomly along the X axis/vector 3 but I have no idea how to go about it. This is the code I've got at the moment:
var thePrefab : GameObject;
function Instantiate () {
var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
}
This makes the prefabs instatiate in the same place as the empty object I put the script in, but I'd like them to only respawn randomly along the X axis/vector 3. Can anyone help me?
Answer by aldonaletto · Jan 07, 2012 at 11:33 PM
Get the empty object's position and add a random value to the x coordinate, then instantiate at this point:
var thePrefab : GameObject; var range: float = 10; // set the +/- range around the empty object
function Instantiate () { var pos = transform.position; // get this object's position pos.x += Random.Range(-range, range); // add a random x offset around it var instance : GameObject = Instantiate(thePrefab, pos, transform.rotation); }
This is exactly what I wanted, thank you so much! Extra kudos for the comments, they really helped me understand what each line of code was doing.
Answer by Julien-Lynge · Jan 07, 2012 at 08:37 PM
You can move along the axes of the current transform with Transform.Translate and get the random component with Unity's Random function. As an example:
var newTransform = transform.position;
newTransform.Translate(Vector3.right * Random.Range(-10.0, 10.0));
var instance : GameObject = Instantiate(thePrefab, newTransform, transform.rotation);
Hi, thanks so much for the help, if possible would you be able to edit the code in my first post and add in your code? I tried it and got loads of errors, being a noob at this :P Thank you!
@Pixelen: We usually don't do that. It's easier for other people to have the answer in an answer and not in the OP. @NOAA_Julien: I'm not sure how it works in JS, but in C# you are better off creating a Random variable at the start and using it throughout the whole class or even the whole program. Reason for this is that it's based on time. The machine updates its time only every x ms, and updates can happen in that same timeframe. So you would end up with 2 or 3 prefabs instantiating in the same place if you created a new Random variable every time.
Your answer
Follow this Question
Related Questions
Prevent changing position 1 Answer
How to rotate without a target vector 1 Answer
transform.right to vector3 1 Answer
Follow x rotation of a target object. 1 Answer
Phantom Axis Movement 0 Answers