Comparing 2 Vector3 values

This script is comparing 2 Vector3 (atleast it’s suppose to) and if they are similar the gameObject this script is attached to will be deactivated and will stop moving, I don’t know why this is not working.

using UnityEngine;
using System.Collections;

public class Learning : MonoBehaviour {

    private Vector3 finalPosition = new Vector3 (3, 3, 3);

    void Update () {
        transform.position = Vector3.Lerp (transform.position, new Vector3 (3, 3, 3), 0.5f * Time.deltaTime);
        if (Mathf.Approximately ((transform.position).magnitude, finalPosition.magnitude)) {
            gameObject.SetActive (false);
        }
    }
}

not sure magnitude can be used that way… alternative might be

SetActive(Vector3.Distance(transform.position, finalPosition) > 0)

or

Mathf.Approximately(Vector3.Distance(transform.position, finalPosition), 0)

1 Like

Mathf.Approximately is very, very picky about what it considers approximately the same values - the epsilon value is so small that it’s almost as bad as comparing directly with 0.

As you’re lerping towards a constant point, you’re only going to get very close, but not exactly there. I’d set a minimum treshold for what’s “close enough”, and use that:

if(Vector3.Distance(transform.position, finalPosition) < 0.01f)
1 Like