I used a script to damage an enemy with health, but keeps breaking. Help please

What the script is meant to do is give the enemy Health points, flash white and return back to original within a float 0.2f and then load a particle effect if it dies.

This is the script I am using for this:

{
    private int health = 10;

    private Material matWhite;
    private Material matDefault;
    private UnityEngine.Object explosionRef;
    SpriteRenderer sr;

    void Start()
    {
        sr = GetComponent<SpriteRenderer>();
        matWhite = Resources.Load("WhiteFlash", typeof(Material)) as Material;
        matDefault = sr.material;
        explosionRef = Resources.Load("Explosion");
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Weapon"))
        {
            Destroy(collision.gameObject);
            health--;
            sr.material = matWhite;

            if(health <= 0)
            {
                killSelf();
            }
            else
            {
                Invoke("ResetMaterial", .1f);
            }
        }
      
    }
    void ResetMaterial()
    {
        sr.material = matDefault;
    }

    private void killSelf()
    {
        GameObject explosion = (GameObject)Instantiate(explosionRef);
        explosion.transform.position = new Vector3(transform.position.x, transform.position.y + .3f, transform.position.z);
        Destroy(gameObject);
    }
}

This is the error message I’m getting:
MissingReferenceException: The object of type ā€˜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.
PlayerController+<g__doAttack|15_0>d.MoveNext () (at Assets/MyScripts/PlayerController.cs:70)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Scripting/Coroutines.cs:17)

This is the PlayerController script:

public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private Rigidbody2D myRigidbody;
public float jumpSpeed;

public Transform groundCheck;
public float groundCheckRad;
public LayerMask whatIsGround;

public bool isGrounded;

private Animator myAnim;

public Vector3 respawnPos;

public LevelManager thelevelManager;

bool isAttacking = false;
private float timebtwAttack;
public float startTimeAttack;

[SerializeField]
GameObject attackHitbox;

// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent();
myAnim = GetComponent();

respawnPos = transform.position;

thelevelManager = FindObjectOfType();
}

// Update is called once per frame

void Update()
{
if(Input.GetButton(ā€œFire1ā€) && !isAttacking)
{
isAttacking = true;
float delay = 0;
int index = UnityEngine.Random.Range(1, 4);
myAnim.Play(ā€œattackā€ + index);

StartCoroutine(doAttack(delay));

}
else if (isGrounded)
{
if (!isAttacking)
{
myAnim.Play(ā€œIdleā€);

}
}

IEnumerator doAttack(float delay)
{
attackHitbox.SetActive(true);
yield return new WaitForSeconds(delay);
attackHitbox.SetActive(false); // This is line 70
isAttacking = false;

}

isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRad, whatIsGround);

if(Input.GetAxisRaw (ā€œHorizontalā€) > 0f )
{
myRigidbody.velocity = new Vector3(moveSpeed, myRigidbody.velocity.y, 0f);
transform.localScale = new Vector3(1f, 1f, 1f);
} else if (Input.GetAxisRaw(ā€œHorizontalā€) < 0f)
{
myRigidbody.velocity = new Vector3(-moveSpeed, myRigidbody.velocity.y, 0f);
transform.localScale = new Vector3(-1f, 1, 1f);
} else
{
myRigidbody.velocity = new Vector3(0f, myRigidbody.velocity.y, 0f);
}

if(Input.GetButtonDown (ā€œJumpā€) && isGrounded)
{
myRigidbody.velocity = new Vector3(myRigidbody.velocity.x, jumpSpeed, 0f);
}
myAnim.SetFloat(ā€œSpeedā€, Mathf.Abs(myRigidbody.velocity.x));
myAnim.SetBool(ā€œGroundā€, isGrounded);

}
void resetAttack()
{
isAttacking = false;
}

void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == ā€œKillPlaneā€)
{
//gameObject.SetActive(false);
//transform.position = respawnPos;
thelevelManager.Respawn();
}
if(other.tag == ā€œCheckPointā€)
{
respawnPos = other.transform.position;
}
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == ā€œMovingPlatformā€)
{
transform.parent = other.transform;
}
}
void OnCollisionExit2D(Collision2D collision)
{
transform.parent = null;
}
}

[/code]

Try delaying your Destroy() method like this:

Destroy(gameObject, 0.5f); // Wait half a second before destroying gameObject

You are a God. Thank you.

1 Like