Mohit Saxena Mohit Saxena - 1 year ago 88
C# Question

how can i get the location of the player along a specific axis during play mode?

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

Answer Source

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.


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 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.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download