Storing a vector3 in C# and checking if its changed

Hi i’m trying to figure out how to store a vector3 in C# and then check if its changed a second or two later to tell if something has moved, i’m not really sure how to do this and any help would be much appreciated.

There are two ways to do what you want to do, the passive way and the active way.

You are going for the passive way:

public class Check:MonoBehaviour{
   Vector3 prevPos;
   Transform obj;

   void Start(){
      prevPos = obj.position;
      InvokeRepeating("CheckForMove",0.001f,1f);
   }
   void CheckForMove(){
      if(prevPos != obj.position){
           // Do something
           prevPos = obj.position;
      }
   }
}

So your object is frequently checking for new position and if it is different then a method is called and the new position is stored for next round.

Now here is the active way:

public class MovingObjext:MonoBehaviour{
    public delegate void MoveHandler();
    public static event MoveHandler OnMove = new MoveHandler(()=>{});
    Vector3 prevPos;
    void Start(){
       prevPos = transform.position;
       InvokeRepeating("CheckMove",0.001f,1f);
    }
    void CheckMove(){
       if(prevPos != transform.position)OnMove();
    }
}

then the other one becomes:

public class Check:MonoBehaviour{

   void Start(){
      MovingObject.OnMove += ActionOnMove;
   }
   void ActionOnMove(){
      // Object has moved, action is done
   }
}

The second one is more complex since it uses event but it has the advantage of getting more simple if you were to have many objects to look after.

If you were to have 100 of MovingObject, it means Check needs to know about all of them, probably in a list and iterating through the list every second so you need to make sure you maintain the list so that when one is destroyed or created, the list is also updated.

The second case works just as it is, whether you add or remove a MovingObject, no difference. The Check method is subscribed to the event so when any of the MovingObject is actually moving, the OnMove event calls any method subscribed to it. In our case the ActionOnMove.

The declaration of the event happens as such:

// A delegate is declared
public delegate void MoveHandler();
// An event instance is declared using the delegate type
// An empty method is assigned to it to avoid null reference
// (the little fancy part ()=>{}) 
public static event MoveHandler OnMove = new MoveHandler(()=>{});

The subscription happens in the Start:

 MovingObject.OnMove += ActionOnMove;