Search Unity

Cant Spawn my Player

Discussion in 'Scripting' started by Actnshj200, Nov 27, 2017.

  1. Actnshj200

    Actnshj200

    Joined:
    Mar 7, 2017
    Posts:
    9
    I cant figure out whats wrong with this code I keep getting a null reference exception error but my player is referenced correctly maybe y'all can find what is wrong with this code.


    public class PlayerSpawner : MonoBehaviour {

    public enum SpawnState { Spawning, Waiting, Counting };

    [System.Serializable]
    public class Wave
    {
    public string name;

    public int count;
    public float rate;
    }
    private healthBar health;
    public Wave[] waves;
    private int nextWave = 0;
    public int Recorder = 0;
    public float timeBetweenWaves = 5f;
    public float waveCountdown;
    private float searchCountdown = 1f;
    public GameObject[] spawnPoints;
    public GameObject enemy;
    public SpawnState state = SpawnState.Counting;

    void Awake()
    {
    waveCountdown = timeBetweenWaves;
    health = FindObjectOfType<healthBar>();
    }

    // Use this for initialization
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {
    if (state == SpawnState.Waiting)
    {
    if (!EnemyIsAlive())
    {
    WaveCompleted();
    }
    else
    {
    return;
    }
    }


    if (waveCountdown <= 0)
    {
    if (state != SpawnState.Spawning && !GameObject.FindGameObjectWithTag("Player").activeInHierarchy)
    {


    StartCoroutine(SpawnWave(waves[nextWave]));


    }
    }
    else
    {
    waveCountdown -= Time.deltaTime;
    }
    }

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

    if (GameObject.FindGameObjectWithTag("Player") == null)
    {
    return false;
    }
    }

    return true;
    }

    void WaveCompleted()
    {
    state = SpawnState.Counting;
    waveCountdown = timeBetweenWaves;

    if (nextWave + 1 > waves.Length - 1)
    {
    nextWave = 0;
    print("All waves Complete");

    }



    else
    {
    nextWave++;
    }

    }



    IEnumerator SpawnWave(Wave _wave)
    {

    state = SpawnState.Spawning;
    for (int i = 0; i < _wave.count; i++)
    {
    SpawnEnemy();
    Recorder= _wave.count;
    yield return new WaitForSeconds(1f / _wave.rate);
    }

    if(_wave.count == 3)
    {
    _wave.count = 1;
    }
    state = SpawnState.Waiting;

    yield break;

    }

    void SpawnEnemy()
    {




    //GameObject _sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
    Instantiate(enemy, transform.position, transform.rotation);
    //Instantiate(Resources.Load("US_Ranger"), transform.position, transform.rotation);
    }
    }
     

    Attached Files:

  2. AcePilot10

    AcePilot10

    Joined:
    Aug 11, 2016
    Posts:
    34
    First off, pleas use the Insert button to insert your code. Also, please put your full error log so we can see where the error is occurring.