Reputation: 189
my player runs forward during play time so what i want to do is store his current position along a specific axis lets say z in a variable inside the update function and use that position elsewhere. i also want to know what kind of datatype we have to use to store such value like the current position of player on the z axis if doing so is even possible. i saw this code somewhere:-
var playerPos:Vector3 = playerObject.transform.position;
but idk how its working if it is in the first place
Upvotes: 1
Views: 741
Reputation: 125315
You are close but the current syntax in your code is for Javascript.
You use transform.position
to get the position of all axis. transform.position
returns a Vector3
and that Vector3
contains all axis for your GameObject position.Vector3
has x
, y
and z
properties which are all float
datatype.
ACCESSING THE POSITION:
Assuming that playerObject
is the name of your GameObject, below is an example of how to access each individual axis.
To get the X axis
float x = playerObject.transform.position.x;
To get the Y axis
float y = playerObject.transform.position.y;
To get the Z axis
float z = playerObject.transform.position.z;
You can also get the position once and store it into a Vector3
variable then access each individual axis from there:
To get the All axis (x,y,z)
Vector3 playerPos = playerObject.transform.position;
float x = playerPos.x;
float y = playerPos.y;
float z = playerPos.z;
MODIFYING THE POSITION:
Modifying the position is different from accessing the it. You can access like this
float x = playerObject.transform.position.x;
but cannot change the x
like this:
playerObject.transform.position.x = 6f;
You must create a new Vector3
, modify the axis you want to (x
, y
and z
), then change the transform.position
variable with that new variable(Vector3
).
It should something like this:
Vector3 newPos = playerObject.transform.position;
newPos.x = 5f;
newPos.y = 4f;
newPos.z = 3f;
playerObject.transform.position = newPos;
My suggestion to you is to always use the Documentation. It shows you what each property or method returns. This will prevent you from asking such question like this. For example, the Transform.position returns Vector3
.
When you click on that Vector3
, you will see many other variables you can access from it.
Upvotes: 2
Reputation: 2989
Your code snippet is in javascript.
The player position is a Vector3
where the single values (x, y and z) are floats. So this will give you the single values:
Vector3 pos = playerObject.transform.position;
float x = pos.x;
float y = pos.y;
float z = pos.x;
This can be shortened, but for the purpose of demonstration I did it like this. Obviously you need to get the playerObject
in some way.
Doing something like this is like the very basics of coding in unity, so if you aren't familiar with that I'd recommend you have a look on the unity tutorials here -> https://unity3d.com/learn/tutorials
Upvotes: 1