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 ();
}
}
}