Search code examples
c#unity-game-enginenullspawn

Spawn System in Unity, Destroying Spwans


I'm making a spawn system for my game, that spawns enemies at random positions, but Unity is telling me that I'm not checking if the object is already destroyed. I've tried to solve it with some other topics here but I couldn't do it. Here is my code:

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

public class EnemySpawn : MonoBehaviour {

    public GameObject Enemy2Spawn;
    public float maxWidth;
    public float minWidth;
    public float rateSpwan;
    private float currentRSpawn = 2.0f;
    public int maxInimigo;
    public int Inimigos = 0;

    void Start()
    {
        transform.position = new Vector3(0, 6.03f, 0);
    }

    // Update is called once per frame
    void Update()
    {
        if (currentRSpawn > Time.time & Inimigos<=maxInimigo)
        {
            transform.position = new Vector3(Random.Range(minWidth, maxWidth), transform.position.y, transform.position.z);
            Instantiate(Enemy2Spawn);
            currentRSpawn = currentRSpawn + rateSpwan;
            Inimigos++;
        }

        if (Enemy2Spawn. == null)
        {
            Destroy(this.gameObject);
        }
    }
}

The error I'm getting is:

"The object of type 'GameObject' has been already destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object"


Solution

  • In the Update function, you are checking if the GameObject is null, which means that it does not exist, then you are using Destroy() to destroy that object that does not exist. Instead, you will want to check if the object exists in the if statement that spawns the enemies. Add that to the if statement, like this, and you should be good.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class EnemySpawn : MonoBehaviour {
    
        public GameObject Enemy2Spawn;
        public float maxWidth;
        public float minWidth;
        public float rateSpwan;
        private float currentRSpawn = 2.0f;
        public int maxInimigo;
        public int Inimigos = 0;
    
        void Start()
        {
            transform.position = new Vector3(0, 6.03f, 0);
        }
    
        // Update is called once per frame
        void Update()
        {
            if (currentRSpawn > Time.time && Inimigos <= maxInimigo && Enemy2Spawn == null)
            {
                transform.position = new Vector3(Random.Range(minWidth, maxWidth), transform.position.y, transform.position.z);
                Instantiate(Enemy2Spawn);
                currentRSpawn = currentRSpawn + rateSpwan;
                Inimigos++;
            }
        }
    }