- Hey guys, sorry for the long one but I’m having abit of an issue with the space invaders game. I’m working on getting the aliens to fire back which works fine until they are destroyed and then i get an error
MissingReferenceException: The object of type 'UnityEngine.GameObject' has been 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.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.GameObject.get_transform () (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
basicAlien.shoot () (at Assets/Scripts/basicAlien.cs:36)
basicAlien.Update () (at Assets/Scripts/basicAlien.cs:29)
The way I’m handling shooting is to create a timer and then shoot every 3 seconds like this using a basicAlien script:
private float shootTimer = 3f;
private const float shootTime = 3f;
public static List<GameObject> allAliens = new List<GameObject>();
void Start()
{
foreach (GameObject alien in GameObject.FindGameObjectsWithTag("alien")) {
allAliens.Add(alien);
}
}
void Update()
{
if (shootTimer <= 0) {
shoot();
}
shootTimer -= Time.deltaTime;
}
private void shoot() {
Vector2 enemyBulletPosition = allAliens[Random.Range(0, allAliens.Count)].transform.position;
GameObject enemyBullet = Instantiate(spawnEnemyBullet, enemyBulletPosition + (Vector2.down * 0.8f), Quaternion.identity);
//GetComponent<AudioSource>().Play();
Destroy(enemyBullet, 1.0f);
shootTimer = shootTime;
}
}
Next, on my playerBullet script I have this, which calls a different alien script kill method:
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.CompareTag("alien")) {
collision.gameObject.GetComponent<alien>().kill();
Destroy(gameObject);
}
}
Here is that separate alien script:
public GameObject explosion;
public void kill() {
//GameManager.increaseScore();
//GetComponent<AudioSource>().Play();
basicAlien.allAliens.Remove(gameObject);
GameObject alienExplosion = Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(alienExplosion, 0.2f);
Destroy(gameObject);
}
I can’t quite work out why the object is still trying to be accessed after it has been destroyed, as the remove is called before the object is destroyed, so it should no longer be in the list when the shoot method is called. I’m at abit of a loss!