Spawn Point

Hi guys, I have this spawn script that works fine, but I would like to add an OnTriggerEnter function where enemies only spawn when the player gets close to the spawnpoint. Can anyone help me do this? I would not be asking if i knew how to do it, but I’m getting desperate as it is the only thing not working properly. Cheers!

public class Spawn : MonoBehaviour
{
public GameObject zombie;
public float delayTime = 4f;

IEnumerator Start()
{
    var obj = Instantiate(zombie, transform.position, transform.rotation) as  GameObject;
    yield return new WaitForSeconds(delayTime);
    StartCoroutine(Start());
}

}

Put a collider component on an object that has this script, check IsTrigger checkbox on the component and put a tag “Player” on your players game object (in Inspector window, just above the Transform values).

public GameObject zombie;

public void OnTriggerEnter(Collider other)
{
        if ((other.tag == "Player")) //checks if it is Player that entered this trigger
        {
         var obj = Instantiate(zombie, transform.position, transform.rotation) as                GameObject;
        }             
}

Here’s one solution:

  1. Set the player’s tag to “Player”.

  2. Add a SphereCollider to your spawnpoint. Set the radius to the maximum distance at which it should detect the player. Check “Is Trigger”.

  3. Change Spawn.cs to:

    public class Spawn : MonoBehaviour {

     public GameObject zombie; 
     public float delayTime = 4f;
     private const string PlayerTag = "Player";
     private bool isPlayerNearby = false;
    
     void Start() {
         StartCoroutine(Spawn());
     }
    
     IEnumerator Spawn() {
         while (true) {
             if (isPlayerNearby) Instantiate(zombie, transform.position, transform.rotation) as  GameObject;
             yield return new WaitForSeconds(delayTime);
         }
     }
    
     void OnTriggerEnter(Collider other) {
         if (string.Equals(other.tag, PlayerTag)) isPlayerNearby = true;
     }
    
     void OnTriggerExit(Collider other) {
         if (string.Equals(other.tag, PlayerTag)) isPlayerNearby = false;
     }
    

    }