Auto Movement System​​​​​​​ in unity

MovementSystem

using UnityEngine;
using UnityEngine.Events;

public class MovementSystem : MonoBehaviour
{
    internal float dist;
    internal int DestinationCounter;
    internal float DefaultMovementVelocity = 1;

    public Point[] Points;

    public bool Loop = false;

    public UnityEvent FirstEvent;
    public UnityEvent FinalEvent;

    [System.Serializable]
    public class Point
    {
        public GameObject Destination;
        public UnityEvent ReachPointEvent;
        public float MovementVelocity = 1;
        public bool LookAtDestination = false;
    }



    private void Start()
    {
        if (FirstEvent != null)
        {
            FirstEvent.Invoke();
        }
    }

    void Update()
    {
        if (Points[DestinationCounter].Destination != null)
        {
            dist = Vector3.Distance(transform.position, Points[DestinationCounter].Destination.transform.position);
        }

        if (dist > 0.5f) // object needs to move yet
        {
            transform.position = Vector3.Lerp(transform.position, Points[DestinationCounter].Destination.transform.position, Points[DestinationCounter].MovementVelocity * Time.deltaTime);
        }

        if (dist <= 0.5f) // object is in the target position
        {
            if (Points.Length != 1)
            {
                DestinationCounter++;

                if (Points[DestinationCounter-1].ReachPointEvent != null)
                {
                    Points[DestinationCounter-1].ReachPointEvent.Invoke();
                }

                if (Points.Length == DestinationCounter && Loop == false)
                {
                    DestinationCounter --;

                    if (FinalEvent != null)
                    {
                        FinalEvent.Invoke();
                    }
                }
            }

            if (Loop == true)
            {
                if (Points.Length == DestinationCounter)
                {
                    DestinationCounter = 0;
                }
            }
        }

        if (Points[DestinationCounter].LookAtDestination == true) 
        {
            transform.LookAt(Points[DestinationCounter].Destination.transform.position);
        }

    }

    public void ChangeColorToGreen()
    {
        GetComponent<Renderer>().material.color = Color.green;
    }

    public void ChangeColorToRed()
    {
        GetComponent<Renderer>().material.color = Color.red;
    }

    public void ChangeColorToBlue()
    {
        GetComponent<Renderer>().material.color = Color.blue;
    }
}


Content ©2023 Abolfazl Tanha All Rights Reserved​​​​​​​