Hello,
I want to check the localPosition of a gameObject compared to the Canvas, but this gameObject is a great great great (etc) grandson of another gameObject. How could i do ?
Thanks !
Code
1st copy paste the following code in a new c# script in unity assets folder
2nd attach it to the gameobject whose position you want to know compared to canvas’s game position
And at last refrence the canvas in the scene in unity editor inspector.
Following is the code with pictures to show it working:-
using UnityEngine;
public class testable : MonoBehaviour
{
[SerializeField] Transform canvas;
void Start()
{
// Get the desired result and store in a variable
Vector3 localPositionParentingCanvas = transform.position - canvas.position;
// Show the result Vector3 in console logs
Debug.Log(localPositionParentingCanvas);
}
}
Explanation
When a gameobject is given a new parent it’s local space changes therefore localPosition changes, but position is not changed as it is in the world space. The new localPosition is a Vector3 position in the space which has the new parent as the origin. Therefore in the new local space the parent transform has position Vector3.zero
What I do in the code is to calculate the displacement of origin and then add it to the world position of the gameobject. I do this because each position is displaced by equal magnitude on all axes in the new local space. And the code I have given above is the short hand of the long code to do that.
Following would be the full long form of the code to do this as I explained above.
// Original origin in world space is (0,0,0)
Vector3 OldWorldOrigin = Vector3.zero;
// World space of the new origin is the position of canvas
Vector3 NewLocalOrigin = canvas.position;
// Claculate the displacement of the origin
Vector3 displacement = OldWorldOrigin - NewLocalOrigin;
// Get the localPosition of our gameobject by adding displacement,
// since displacement remains same for all gameobjects
Vector3 localPositionParentingCanvas = transform.position + displacement;
This can be shortened in one line as :
Vector3 localPositionParentingCanvas = transform.position + Vector3.zero - canvas.position;
Since Vector3.zero is 0 on all axes thus Vector3.zero - newVector3 = (-newVector3), and so the final short form of code comes to be:
Vector3 localPositionParentingCanvas = transform.position - canvas.position;