- Home /
The question is answered, right answer was accepted
Store x y z position of gameobject in var.
Hello :)
For my script donjon room generator, i need to calculate the space between the doors of my rooms. - I need to store in separated var the position of every room.
I have try this but return always 0 :
private var xadresse : float;
private var zadresse : float;
function Update () {
var xadresse = transform.position.x ;
var zadresse = transform.position.z ;
}
function OnGUI ()
{
GUI.Box(Rect(60,200,130,50),"x :" + xadresse);
GUI.Box(Rect(60,250,130,50),"z :" + zadresse);
}
Answer by Cornelis-de-Jager · Jul 18, 2017 at 04:36 AM
Within your update function, you are creating new variables. Then immediately throwing them away. Do the following:
private var xadresse : float; private var zadresse : float;
function Update () {
xadresse = transform.position.x ; // Remove var
zadresse = transform.position.z ; // Remove var
}
function OnGUI ()
{
GUI.Box(Rect(60,200,130,50),"x :" + xadresse);
GUI.Box(Rect(60,250,130,50),"z :" + zadresse);
}
The reason for this is you create a new variable each time you use
var
so best to only use it once.
This is correct. As @Cornelis-de-Jager says, you're creating new variables called 'xadresse' and 'zadresse' each time the Update function is called. This is because in Unityscript (as in Javascript) uses var keyword to create a new variable in the scope you are defining it.
This is, that if you write : var myVariable
inside a function like Update, your variables are being defined only inside that function and if you write them outside any function (i.e. the global scope) these variables can be accesed inside the rest of the functions but any variable defined with the same name inside a function will "hide" the global variable.