- Home /
[2D] Get the position of an object outside the scope
Hello dear community! I am stuck with a silly problem. How do you get the position of an object from the other script? The problem, as I understand it - the line of code needed, can only be called from an Update block and therefore cannot be accessed from the other script. Can you help me please? In my case: I want a rocket to spawn not in the middle of the screen, but inside the character. For this reason, I assume I need to know where the character in space is positioned.
My script so far:
//move.js
function Start()
{
}
function Update()
{
var playertrans = this.transform.position.x;
var playertransy = this.transform.position.y;
//Here, inside Update scope {Debug.Log(playertrans) works pefectly};
// the rest of the movement script
}
//shooting.js
var script : move;
script = GetComponent("move");
function Update(){
Debug.Log(script.playertrans);
// Here Debug.Log(script.playertrans) returns null as if it doesn't have the access to the block of code containing the value
// the rest of the shooting script
}
Answer by Saad_Khawaja · Jul 17, 2014 at 02:03 PM
You are creating a variable inside the Update function so it's scope is limited. What you need is a public variable in move.js so that the value remains outside the scope of the function.
However, since you only want the position. You don't need to store it anywhere as it can be accessed by GameObject.transform.position;
For example:
In your shooting.js script, you can call: GameObject.Find("MoveGameObjectName").transform.position;
to get the position of any gameobject in your scene.
Answer by Fewpwew130 · Jul 17, 2014 at 02:43 PM
Saad_Khawaja, thank you very much! It works perfectly! =)
Your answer
Follow this Question
Related Questions
Vector3.Lerp works outside of Update() 3 Answers
Transform position not changing. 2 Answers
Getting Transform position using mouse position 3 Answers
Update instantiates more than 1 object 2 Answers
Does it help performance to first check if some transform attribute has changed before setting it? 1 Answer