0
\$\begingroup\$

I have been making a C# script that attacks the player in Unity. However, with the following code I got the following error message:

"The object of type 'GameObject' has been destroyed but you are still trying to access it.

Here is my code:

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

public class attackPlayer : MonoBehaviour {

    GameObject Enemy;
    GameObject Player;

    void Start ()
    {
        Enemy =  GameObject.FindWithTag ("Enemy");
        Player = GameObject.FindWithTag ("Player");
    }

    void Update ()
    {
        var heading = Enemy.transform.position.x - Player.transform.position.x;
        if (heading > 0.0f && heading < 5.0f) 
        {
            Explode ();
        }
    }

    void Explode() 
    {
        var exp = GetComponent <ParticleSystem>();
        exp.Play ();

        Destroy (gameObject,exp.main.duration);
        Destroy(Player);
    }

    void OnCollisionEnter2D (Collision2D col)
    {
        if (col.gameObject.tag == "Player") 
        {
            Explode ();
        }
    }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In Explode, you destroy the Player game object. In Update, you calculate the distance between the enemy and the player: var heading = Enemy.transform.position.x - Player.transform.position.x;. This calculation still references the player, which is destroyed in Explode.

I'm not very familiar with Unity techniques on handling this, but I could see that one solution is to set Player = null; after calling Destroy(Player); and checking if Player is not null in Update before doing the calculation.

\$\endgroup\$
2
  • \$\begingroup\$ After adding if ((Player != null) && Enemy !=null ){ var heading = Enemy.transform.position.x - Player.transform.position.x; if (heading > 0.0f && heading < 1.0f) { Explode (); }It works!...Thank you very much @Tyyppi_27! \$\endgroup\$
    – Haileapp
    Mar 30, 2017 at 8:09
  • \$\begingroup\$ Your very welcome @Haileapp. Please accept my answer so that others can find help in the future more easily! \$\endgroup\$
    – user35344
    Mar 30, 2017 at 9:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .