Spawn enemies out of sight on top of navmesh

32 Views Asked by At

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++;
                }
            }
        }
    }
}
0

There are 0 best solutions below