Getting rid of Character Controller gives me an error

I’m trying to play a death animation on enemy death and I feel like I’ve almost got it. Here’s my EnemyGruntDeadState

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

public class EnemyGruntDeadState : EnemyGruntBaseState
{
    private readonly int DeathHash = Animator.StringToHash("Death"); //("Animation Name")
    private const float CrossFadeDuration = 0.1f;
    public EnemyGruntDeadState(EnemyGruntStateMachine stateMachine) : base(stateMachine){}
    public override void Enter()
    {
        stateMachine.Weapon.gameObject.SetActive(false);
        GameObject.Destroy(stateMachine.Target);
        // stateMachine.Controller.gameObject.SetActive(false); //this makes the corpse disappear.
        GameObject.Destroy(stateMachine.Controller); //If I don't destroy this, the collider stays up forever.
        // if I do, I get the error message. But everything runs well.
        // How do I stop looking for this CharacterController after death? 
        
        stateMachine.Animator.CrossFadeInFixedTime(DeathHash, CrossFadeDuration);
    }
    public override void Tick(float deltaTime)
    {
    }
    public override void Exit()
    {
    }
}

The problem is that if I run it as is, I get a MissingReferenceException telling me “The object of type 'CharacterController has been destroyed but you are still trying to access it.”

How do I stop trying to access it?

Update, it’s trying to read from my ForceReceiver here

 private void Update()
    {
        if (verticalVelocity < 0f && controller.isGrounded)
        {
            verticalVelocity = Physics.gravity.y * Time.deltaTime;
        }
        else
        {
            verticalVelocity += Physics.gravity.y * Time.deltaTime;
        }

What would be the best way to disable the controller in this on death?

Rather than destroying the CharacterController, you could simply disable it

stateMachine.Controller.enabled=false;
1 Like

Thank you again! That fixed it.

I feel like I’m still at the point where I have a hard time translating “what do I want” to “what should the code look like?” even after looking at the API.

Don’t worry, you will. Practice makes perfect. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms