- Home /
Question by
marshrover · Sep 22, 2014 at 09:06 PM ·
instantiateobjectrandomrelative position
Instantiate Object at random position relative to another object
How can I instantiate an object relative to another object?
I also do not want the instantiated object to be made a child of the object it is instantiated relative to.
Here is my code:
using UnityEngine;
using System.Collections;
public class Spawning : MonoBehaviour {
public GameObject cubium;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(1 == Random.Range(1, 200)){
Vector3 position = new Vector3(Random.Range(-100.0F, 100.0F), Random.Range(-100.0F, 100.0F), Random.Range(-100.0F, 100.0F));
GameObject clone;
clone = Instantiate(cubium, position, Quaternion.identity) as GameObject;
}
}
}
Comment
Add the position of the other game object to your position
variable. Now it's a point in space +/-100 units from that game object.
Answer by 767_2 · Sep 22, 2014 at 09:13 PM
Vector3 firstObjPos;
void Update () {
if(1 == Random.Range(1, 200)){
Vector3 position = new Vector3(Random.Range(-100.0F, 100.0F), Random.Range(-100.0F, 100.0F), Random.Range(-100.0F, 100.0F));
GameObject clone;
clone = Instantiate(cubium, position+firstObjPos, Quaternion.identity) as GameObject;
}
Answer by kurotatsu · Sep 22, 2014 at 10:16 PM
And here's how to instantiate as a shild of another object:
http://answers.unity3d.com/questions/791626/how-do-instantiate-stuff-as-a-child.html