Waypoints And Waves System

Hi all !

I work on a waves system with waypoints for units when they spawn.
But when units spawn they didn’t go on the waypoint.
My script work if unit is already in the scene but with the wave system units didn’t be in the scene at the begining… So how unit can go on waypoint when units spawn ?

Script waves :

using UnityEngine;
using System.Collections;

public class WaveSpawner : MonoBehaviour {

    public enum SpawnState { SPAWNING, WAITING, COUNTING };

    [System.Serializable]
    public class Wave
    {
        public string name;
        public Transform enemy;
        public int count;
        public float rate;
    }

    public Wave[] waves;
    private int nextWave = 0;

    public Transform[] spawnPoints;

    public float timeBetweenWaves = 5f;
    public float waveCountdown;

    private float searchCountdown = 1f;

    public SpawnState state = SpawnState.COUNTING;

    void Start ()
    {
        if (spawnPoints.Length == 0)
        {
            Debug.LogError("No spawn points referenced");
        }

        waveCountdown = timeBetweenWaves;
    }

    void Update()
    {
        if (state == SpawnState.WAITING)
        {
            if (!EnemyIsAlive())
            {
                WaveCompleted();
            }
            else
            {
                return;
            }
        }

        if (waveCountdown <= 0)
        {
            if (state != SpawnState.SPAWNING)
            {
                StartCoroutine( SpawnWave(waves[nextWave] ) );
            }
        }
        else
        {
            waveCountdown -= Time.deltaTime;
        }
    }
    void WaveCompleted()
    {
        Debug.Log("Wave Completed !");

        state = SpawnState.COUNTING;
        waveCountdown = timeBetweenWaves;

        if (nextWave + 1 > waves.Length - 1)
        {
            nextWave = 0;
            Debug.Log("All waves complete !");
        }

        else
        {
            nextWave++;
        }
    }

    bool EnemyIsAlive()
    {
        searchCountdown -= Time.deltaTime;
        if (searchCountdown <= 0f)
        {

            searchCountdown = 1f;
            if (GameObject.FindGameObjectWithTag("Enemy") == null)
             {
                return false;
             }
        }

        return true;
    }

    IEnumerator SpawnWave(Wave _wave)
    {
        Debug.Log("Spawning Wave : " + _wave.name);
        state = SpawnState.SPAWNING;

        for (int i = 0; i < _wave.count; i++)
        {
            SpawnEnemy(_wave.enemy);
            yield return new WaitForSeconds(1f / _wave.rate);

        }
        state = SpawnState.WAITING;
    

        yield break;
    }

    void SpawnEnemy (Transform _enemy)
    {
        Debug.Log("Spawning Enemy:" + _enemy.name);

        if (spawnPoints.Length ==0)
        {
            Debug.LogError("No spawn points referenced");
        }

        Transform _sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
        Instantiate(_enemy, _sp.position, _sp.rotation);
       
    }


}

RTS Waypoints :

using UnityEngine;
using System.Collections.Generic;

namespace RTSKit
{
    public class RTSWayPoints : MonoBehaviour
    {
        public enum WayPointType
        {
            Cycle,
            PingPong,
            AutoRandom,
        }
        [Tooltip("The waypoint name used to identify each waypoint")]
        public string waypointName = "WayPoint 1";
        [Tooltip("The type of way point for default getting the next waypoint path")]
        public WayPointType wayPointType;
        [Tooltip("if true, the waypoint will auto snap to ground")]
        public bool snapToGround;
        [Tooltip("The ground layer mask used for snap the waypoint path to the ground")]
        public LayerMask groundMask = -1;

        [Tooltip("The waypoint color gizmos, not used in the game")]
        public Color wayPointColor = Color.blue;

        [HideInInspector]
        public List<Transform> waypointPath = new List<Transform>();
        private List<GameObject> pingPongObject = new List<GameObject>();

        void Awake()
        {
            if (transform.childCount >= 1)
            {
                for (int i = 0; i < transform.childCount; i++)
                {
                    Transform child = transform.GetChild(i);
                    waypointPath.Add(child);
                    RaycastHit hit;
                    if (snapToGround && Physics.Raycast(child.position, -child.up, out hit, 100f, groundMask))
                    {
                        child.position = hit.point;
                    }
                }
            }
        }

        /// <summary>
        /// Get the first way point path
        /// </summary>
        /// <returns></returns>
        public Transform GetFirstWayPoint()
        {
            if (waypointPath.Count == 0)
            {
                Debug.LogError("No Waypoint", this);
                return null;
            }
            return waypointPath[0];
        }

        /// <summary>
        /// Get the randomly waypoint path
        /// </summary>
        /// <returns></returns>
        public Transform GetRandomWayPoint()
        {
            if (waypointPath.Count == 0)
            {
                Debug.LogError("No Waypoint", this);
                return null;
            }
            return waypointPath[Random.Range(0, waypointPath.Count - 1)];
        }

        /// <summary>
        /// Get waypoint path by index
        /// </summary>
        /// <param name="pathIndex">the path index to get</param>
        /// <returns></returns>
        public Transform GetWayPoint(int pathIndex)
        {
            if (waypointPath.Count == 0)
            {
                Debug.LogError("No Waypoint", this);
                return null;
            }
            if (pathIndex + 1 > waypointPath.Count)
            {
                pathIndex = 0;
            }
            return waypointPath[pathIndex];
        }

        /// <summary>
        /// Get next waypoint path
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="pathIndex"></param>
        /// <returns></returns>
        public Transform GetNextWayPoint(GameObject obj, ref int pathIndex)
        {
            if (waypointPath.Count == 0)
            {
                Debug.LogError("No Waypoint", this);
                return null;
            }
            if (wayPointType == WayPointType.Cycle)
            {
                pathIndex += 1;
                if (pathIndex + 1 > waypointPath.Count) pathIndex = 0;
            }
            else if (wayPointType == WayPointType.PingPong)
            {
                if (!pingPongObject.Contains(obj))
                {
                    pathIndex += 1;
                    if (pathIndex + 1 > waypointPath.Count)
                    {
                        pathIndex -= 1;
                        pingPongObject.Add(obj);
                    }
                }
                else
                {
                    pathIndex -= 1;
                    if (pathIndex < 0)
                    {
                        pathIndex += 1;
                        pingPongObject.Remove(obj);
                    }
                }
            }
            else if (wayPointType == WayPointType.AutoRandom)
            {
                pathIndex = Random.Range(0, waypointPath.Count - 1);
            }
            return waypointPath[pathIndex];
        }

        /// <summary>
        /// Get waypoint length
        /// </summary>
        /// <returns></returns>
        public int GetWayPointLength()
        {
            return transform.childCount;
        }

#if UNITY_EDITOR
        void OnDrawGizmos()
        {
            if (wayPointType == WayPointType.Cycle || wayPointType == WayPointType.PingPong)
            {
                //Show the waypoint connection
                if (transform.childCount > 1)
                {
                    for (int i = 0; i < transform.childCount; i++)
                    {
                        Transform child = transform.GetChild(i);
                        Vector3 drawPos = child.position;
                        if (snapToGround)
                        {
                            RaycastHit hit;
                            if (Physics.Raycast(child.position, -child.up, out hit, 100f, groundMask))
                            {
                                drawPos = hit.point;
                            }
                        }
                        Gizmos.color = wayPointColor;
                        Gizmos.DrawWireSphere(drawPos, 0.5f);
                        Transform nexPos = null;
                        if (i + 1 < transform.childCount)
                        {
                            nexPos = transform.GetChild(i + 1);
                        }
                        else if (wayPointType == WayPointType.Cycle)
                        {
                            nexPos = transform.GetChild(0);
                        }
                        if (nexPos != null)
                        {
                            Vector3 nexLoc = nexPos.position;
                            if (snapToGround)
                            {
                                RaycastHit hit;
                                if (Physics.Raycast(nexPos.position, -nexPos.up, out hit, 100f, groundMask))
                                {
                                    nexLoc = hit.point;
                                    nexLoc.y += 0.1f;
                                    drawPos.y += 0.1f;
                                }
                            }
                            Gizmos.color = Color.green;
                            Gizmos.DrawLine(drawPos, nexLoc);
                        }
                    }
                }
            }
            else if (wayPointType == WayPointType.AutoRandom)
            {
                if (transform.childCount > 1)
                {
                    bool childSelected = false;
                    for (int i = 0; i < transform.childCount; i++)
                    {
                        Transform child = transform.GetChild(i);
                        if (UnityEditor.Selection.activeGameObject == child.gameObject)
                        {
                            childSelected = true;
                        }
                    }
                    if (!childSelected)
                    {
                        //Show the waypoint connection
                        for (int i = 0; i < transform.childCount; i++)
                        {
                            Transform child = transform.GetChild(i);
                            Vector3 drawPos = child.position;
                            if (snapToGround)
                            {
                                RaycastHit hit;
                                if (Physics.Raycast(child.position, -child.up, out hit, 100f, groundMask))
                                {
                                    drawPos = hit.point;
                                }
                            }
                            Gizmos.color = wayPointColor;
                            Gizmos.DrawWireSphere(drawPos, 0.5f);
                            foreach (Transform tr in transform)
                            {
                                if (tr == child) continue;
                                Vector3 nextLoc = tr.position;
                                Vector3 curLoc = drawPos;
                                if (snapToGround)
                                {
                                    RaycastHit hit;
                                    if (Physics.Raycast(tr.position, -tr.up, out hit, 100f, groundMask))
                                    {
                                        nextLoc = hit.point;
                                        nextLoc.y += 0.1f;
                                        curLoc.y += 0.1f;
                                    }
                                }
                                Gizmos.color = Color.green;
                                Gizmos.DrawLine(curLoc, nextLoc);
                            }
                        }
                    }
                    else
                    {
                        //Show the waypoint connection
                        for (int i = 0; i < transform.childCount; i++)
                        {
                            Transform child = transform.GetChild(i);
                            Vector3 drawPos = child.position;
                            if (snapToGround)
                            {
                                RaycastHit hit;
                                if (Physics.Raycast(child.position, -child.up, out hit, 100f, groundMask))
                                {
                                    drawPos = hit.point;
                                }
                            }
                            Gizmos.color = wayPointColor;
                            Gizmos.DrawWireSphere(drawPos, 0.5f);
                            if (UnityEditor.Selection.activeGameObject == child.gameObject)
                            {
                                foreach (Transform tr in transform)
                                {
                                    if (tr == child) continue;
                                    Vector3 nextLoc = tr.position;
                                    Vector3 curLoc = drawPos;
                                    if (snapToGround)
                                    {
                                        RaycastHit hit;
                                        if (Physics.Raycast(tr.position, -tr.up, out hit, 100f, groundMask))
                                        {
                                            nextLoc = hit.point;
                                            nextLoc.y += 0.1f;
                                            curLoc.y += 0.1f;
                                        }
                                    }
                                    Gizmos.color = Color.green;
                                    Gizmos.DrawLine(curLoc, nextLoc);
                                }
                            }
                        }
                    }
                }
            }
        }
#endif
    }
}

Unit Fallow Waypoints :

using UnityEngine;
using System.Collections;
using RTSKit;

/// <summary>
/// This script used for unit to follow the waypoint.
/// the unit will move when unit not using ability.
/// </summary>
public class UnitFollowWaypoint : MonoBehaviour {
	[Tooltip("the unit object for move to the next waypoint

if null, it will get from its game object")]
public Unit unit;
[Tooltip(“if true, this waypoint will be active only when unit is controlled by AI”)]
public bool useOnlyForAI = true;

	[Header("Way Point")]
	[Tooltip("the waypoint script used to get the waypoint path

Leave it null to auto find waypoint by waypoint name")]
public RTSWayPoints wayPointScript;
[Tooltip(“The waypoint name used to find it when waypoint script is null”)]
public string waypointName = “WayPoint 1”;
public int startingPathIndex;
public bool limitPatrolLoop;
public int loopCount = 1;

	[Tooltip("if true, the unit will auto patrol in waypoint at start of the game.")]
	public bool autoPatrol = true;
	[Tooltip("Time to check the unit for getting next waypoint when auto patrol is true")]
	public float checkTime = 0.5f;
	[Tooltip("Time to start patrol at start")]
	public float startPatrolTime = 0.5f;

	private bool hasMove;
	private int currentPath = 0;
	private int currentLoop;

	// Use this for initialization
	void Start() {
		if(unit == null) {
			unit = GetComponent<Unit>();
		}
		if(useOnlyForAI && !unit.playerManager.isHuman) {
			if(wayPointScript == null) {
				RTSWayPoints[] waypoints = FindObjectsOfType<RTSWayPoints>();
				foreach(RTSWayPoints waypoint in waypoints) {
					if(waypoint != null && waypoint.waypointName == waypointName) {
						wayPointScript = waypoint;
						break;
					}
				}
			}
			if(wayPointScript != null) {
				currentPath = startingPathIndex;
				StartCoroutine(OnUpdate());
			}
		} else if(!useOnlyForAI) {
			if(wayPointScript == null) {
				RTSWayPoints[] waypoints = FindObjectsOfType<RTSWayPoints>();
				foreach(RTSWayPoints waypoint in waypoints) {
					if(waypoint != null && waypoint.waypointName == waypointName) {
						wayPointScript = waypoint;
						break;
					}
				}
			}
			if(wayPointScript != null) {
				currentPath = startingPathIndex;
				StartCoroutine(OnUpdate());
			}
		}
	}

	IEnumerator OnUpdate() {
		yield return new WaitForSeconds(startPatrolTime);
		while(true) {
			if(autoPatrol && !unit.hasActiveAbility) {
				if(limitPatrolLoop) {
					if(loopCount > currentLoop) {
						Patrol();
					}
				} else {
					Patrol();
				}
			}
			yield return new WaitForSeconds(checkTime);
		}
	}

	public void Patrol() {
		if(hasMove) {
			if(limitPatrolLoop) {
				if(currentPath + 1 == wayPointScript.waypointPath.Count) {
					currentLoop++;
					if(loopCount == currentLoop) {
						return;
					}
				}
			}
			Transform tr = wayPointScript.GetNextWayPoint(unit.gameObject, ref currentPath);
			if(tr != null) {
				unit.Move(tr.position, false);
			}
		} else {
			Transform tr = wayPointScript.GetWayPoint(startingPathIndex);
			if(tr != null) {
				unit.Move(tr.position, false);
				hasMove = true;
			}
		}
	}
}

Script on empty for units :

using UnityEngine; using
System.Collections; 
public class WayPoint : MonoBehaviour
{ 	
        public bool useOnlyIfVisible;
 	public Vector3 raycastLocation;
}

Thanks for your answers
meTonne

Please ? :frowning: