Get Position of a GameObject in Unity 3D with C# Script
During the gameplay, it often may be needed to trace the position of an object in Unity 3D programmatically using C# script. For example, in a car racing game, you need to continuously check the location of each car. In that case, you have to get the position of the game object.
The position of any object in Unity is in the transform component. So we have to get access to the transform component in order to get the current position of a GameObject. Before describing further, let’s see the example below:
public class get3DObjectPosition : MonoBehaviour { void Update() { // Get position from transfrm component Vector3 objectPosition = transform.position; Debug.Log("Position of the Object is: " + objectPosition); } }
Below is the result for the above Unity C# program:
Position of the Object is: (-0.22, 1.62, 3.21)
In the above C# code, I have first created a Vector3 variable that stores the position from the transform component. Then I print it in the console to get the position.
You can notice that I am checking the position of the game object in the Update()
method. In this way, it is possible to continue tracing the location or position of the object in every frame.
Now let’s get x, y and z values separately from the position property:
void Update() { // Get position from transfrm component Vector3 objectPosition = transform.position; Debug.Log("x: " + objectPosition.x); Debug.Log("y: " + objectPosition.y); Debug.Log("z: " + objectPosition.z); }
Leave a Reply