So when my enemy game object get destroy by the player, an error pop up
“MissingReferenceException: The object of type ‘Transform’ 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.”
I’m not sure how to fix this, if anyone can help me that would be great
Here my Script:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
public class PlayerAIBehaviour : MonoBehaviour
{
public float playermaxhealth; //maxhealth
public float playercurrenthealth; //currenthealth
public float damage; //damage
public float speed; //speed
public float attackrange; //attackrange
public bool moving;
private Transform enemy;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
enemy = GameObject.FindGameObjectWithTag("Enemy").transform;
moving = true;
playercurrenthealth = playermaxhealth;
}
// Update is called once per frame
void Update()
{
if (moving == true)
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
float distanceFromEnemy = Vector2.Distance(enemy.position, transform.position);
if (distanceFromEnemy < attackrange)
{
moving = false;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
EnemyBehaviour EnemyScript = other.GetComponent<EnemyBehaviour>();
EnemyScript.TakeDamage(damage);
}
}
public void TakeDamage(float damage) //PlayerTakingDamage
{
playercurrenthealth -= damage;
if (playercurrenthealth <= 0)
{
Destroy(this.gameObject);
}
}
public void SetMaxHealth()
{
playercurrenthealth = playermaxhealth;
}
public void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, attackrange);
}
}