LOL Jovem
LOL Jovem

Reputation: 207

Get initial position of an object in a variable and don't change the value of it

So I want to keep the position of an object in a variable and the value of it never be changed but Im not being able to do it. My code looks like this:

public class Test : MonoBehaviour
{
    Transform InitPosition;

    void Start()
    {
        InitPosition = transform;
        Debug.Log(InitPosition.position);
    }

    void FixedUpdate()
    {
        Debug.Log(InitPosition.position);
    }
}

I know that this code don't do something itself but I just want to see the result of the FixedUpdate Debug.Log be the same as the Start one.

Thank you for your attention.

Upvotes: 1

Views: 398

Answers (1)

Jeff
Jeff

Reputation: 7674

Transform is a class, which means that InitPosition stores a reference to the transform object. So both InitPosition and transform refer to the same object: if the object changes, you'll observe those changes whether you use InitPosition.position or transform.position.

position on the other hand is a Vector3 which is a struct and therefore a value type, which has copy semantics. So store a copy of the position instead:

public class Test : MonoBehaviour
{
    Vector3 InitPosition;

    void Start()
    {
        InitPosition = transform.position;
        Debug.Log(InitPosition);
    }

    void FixedUpdate()
    {
        Debug.Log(InitPosition);
    }
}

Upvotes: 2

Related Questions