Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question How to get enemies to spawn in certain regions?

Discussion in 'Scripting' started by oakysappy, May 12, 2024.

  1. oakysappy

    oakysappy

    Joined:
    Feb 3, 2023
    Posts:
    2
    I'm making a really simple 3D game right now and I'm trying to make it so that enemies will spawn in 3 different regions in my game. My code right now only spawns enemies in a small range but they get stuck in some places where I don't want them to spawn. How can I fix this issue so that I make them spawn in three specific regions of my map?

    Here is my code for my spawn manager so far:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class EnemySpawner : MonoBehaviour
    {
    [SerializeField] private GameObject enemyPrefab;
    [SerializeField] private float enemySpawnInterval = 3.5f;

    public GameObject[] spawnLocations;
    // Start is called before the first frame update
    void Start()
    {
    StartCoroutine(spawnEnemy(enemySpawnInterval, enemyPrefab));
    }

    private IEnumerator spawnEnemy(float interval, GameObject enemy)
    {
    yield return new WaitForSeconds(interval);
    GameObject newEnemy = Instantiate(enemy, new Vector3(Random.Range(-5f, 5), 0.5f, Random.Range(-5f, 5f)), Quaternion.identity);
    StartCoroutine(spawnEnemy(interval, enemy));
    }
    }
     
  2. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,936
    Are you using a NavPath?

    You could define various spawnPoints.
    Then use:
    Code (csharp):
    1.  
    2. //Choose a random position somewhere inside a circle at spawnPoint with radius spawnAreaRadius
    3. Vector2 random = UnityEngine.Random.insideUnitCircle * 5f;
    4. Vector3 randomSpawnPosition = new Vector3 (spawnPoint.x + random.x, spawnPoint.y, spawnPoint.z + random.y);
    5.  
    Then use:
    NavMesh.SamplePosition(randomSpawnPosition, ...)

    to find the nearest point on the navMesh closest to randomPoint.
    https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
     
    Last edited: May 12, 2024
  3. oakysappy

    oakysappy

    Joined:
    Feb 3, 2023
    Posts:
    2
    Im using Unity 2022 and I don't have NavPath automatically. How would I get it?