- Home /
Why can't I instantiate an object that is +5 in the x and z axis?
Hello, I am trying to instantiate an object that is 5 units away in the x and z axis in relative to another object. However, the problem is that the instantiated object will spawn at position 0,0,0 which is located at the corner of my terrain. How do I make the instantiated object to spawn +5 in the x and z axis relative to the emptyObject?
This is the code I use:
#pragma strict
var thePrefab : GameObject;
private var defaultPosition = Vector3(5 + GameObject.Find("EmptyObject").transform.position.x, GameObject.Find("EmptyObject").transform.position.y, 5 + GameObject.Find("EmptyObject").transform.position.z);
function Start () {
Instantiate(thePrefab, defaultPosition, transform.rotation);
}
Answer by robertbu · Jun 16, 2013 at 06:24 AM
You don't want to make multiple GameObject.Find() calls. They are expensive (though the compiler might be smart enough to combine them). In addition, move your initialization logic inside Start(). What you have now did not compile for me. Here is a change to your script that compiles and works:
#pragma strict
var thePrefab : GameObject;
private var defaultPosition : Vector3;
function Start () {
defaultPosition = GameObject.Find("EmptyObject").transform.position;
defaultPosition.x += 5.0;
defaultPosition.z += 5.0;
Instantiate(thePrefab, defaultPosition, transform.rotation);
}
Your answer
Follow this Question
Related Questions
problem whit Instantiate Prefabs position. 0 Answers
How to follow multiple clones positions of an instantiate prefab having a velocity ? 1 Answer
GameObject position and localPosition not changing in hiearchy, only in script. 0 Answers
Setting parent of instantiated object fails (Error: setting parent of prefab is disabled...) 1 Answer
Help making a damage number system 1 Answer