-2

I am trying to animate this healthkit but for some reason it doesn't. I tested it by adding a debug.log and when I press Q I get the error "Object reference not set to an instance of an object". I don't know why it would do this. Thanks for the help!

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

public class Anim_Trigger_for_healthpack : MonoBehaviour
{
    private Coroutine onHealKit = null;
    private Animator anim;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            if (onHealKit == null)
                onHealKit = StartCoroutine(HealthKit());
        }
    }

    IEnumerator HealthKit()
    {
        anim.SetBool("Qpress", true); //bug on this line
        yield return new WaitForSeconds(2.0f);
        anim.SetBool("Qpress", false);
        onHealKit = null;
    }
}
Arya Akhavein
  • 343
  • 1
  • 7

1 Answers1

0

anim is never instantiated. Use anim = gameObject.GetComponent<Animator>(); in Start() to get the reference when the scene begins.

Alternatively you can make it public and just drag and drop the Animator in the inspector.

DekuDesu
  • 2,224
  • 1
  • 5
  • 19