0

I'm trying to spawn enemies out of camera sight, as long as they are on top of a navmesh. This is the code, but for the moment it does nothing. What am I getting wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class EnemySpawner : MonoBehaviour 
{
    private int waveNumber = 0;
    public int enemiesAmount = 0;
    public GameObject Enemy;
    public Camera cam;

    // Use this for initialization
    void Start () 
    {
        cam = Camera.main;
        enemiesAmount = 0;
    }

    // Update is called once per frame
    void Update () 
    {
        float height = cam.orthographicSize + 1;
        float width = cam.orthographicSize * cam.aspect + 1;

        if (enemiesAmount==0) 
        {
            waveNumber++;

            for (int i = 0; i < waveNumber; i++) 
            {
                NavMeshHit hit;

                if(NavMesh.Raycast(cam.transform.position, new Vector3(cam.transform.position.x + Random.Range(-width, width), 3, cam.transform.position.z + height + Random.Range(10,30)), out hit, NavMesh.AllAreas))
                {
                    Debug.Log("Hit");
                    Instantiate(Enemy, new Vector3(cam.transform.position.x + Random.Range(-width, width), 3, cam.transform.position.z + height + Random.Range(10, 30)), Quaternion.identity);
                    enemiesAmount++;
                }
            }
        }
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • what happens when you debug it? – BugFinder Sep 01 '23 at 08:11
  • is `enemiesAmount` ever going to be `0` again? Also have in mind that those `Random.Range` you use for the raycast check will not be the same as the one you use to actually spawn the objects ... maybe you would rather want to store the resulting `Vector3` and use the same for both – derHugo Sep 01 '23 at 08:43
  • also raycast would expect a **direction** as the second parameter ... you are providing a position! It should probably rather be something like `var direction = new Vector3(Random.Range(-width, width), 3f, height + Random.Range(10,30));` and then `if(NavMesh.Raycast(cam.transform.position, direction, out hit, NavMesh.AllAreas))` and `Instantiate(Enemy, cam.transform.position + direction, Quaternion.identity);` – derHugo Sep 01 '23 at 08:47
  • Aaaand finally: If I understand correctly your `if` condition is inverted ... you currently check if you hit something and only then spawn an enemy ... didn't you want to go the other way round: You currently do not hit anything -> spawn enemy which means outside of line of sight ... might also want to use some `while` loop and keep trying to spawn enemies until the entire required wave amount has actually been spawned .. – derHugo Sep 01 '23 at 08:48

0 Answers0