Animation not working in Coroutine, NullReferenceException

Yeah so it says
NullReferenceException: Object reference not set to an instance of an object
CharacterSpawner+d__5.MoveNext () (at Assets/Code/CharacterSpawner.cs:36)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <23a7799da2e941b88c6db790c607d655>:0)
UnityEngine.MonoBehaviour:StartCoroutine(String)
CharacterSpawner:Start() (at Assets/Code/CharacterSpawner.cs:27)

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

public class CharacterSpawner : MonoBehaviour
{
    public GameObject characterKnight;
    public GameObject characterWizard;
    public bool cameraTarget;

    private InventoryUI inventory;

    void Start()
    {
        if (CharacterSelection.knight == true)
        {
            StartCoroutine("Knight");
        }
        if (CharacterSelection.wizard == true)
        {
            StartCoroutine("Wizard");
        }

        if (CharacterSelection.knight == false && CharacterSelection.wizard == false)
        {
            StartCoroutine("Knight");
        }
        inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<InventoryUI>();
    }

    IEnumerator Knight()
    {
        Instantiate(characterKnight, transform.position, characterKnight.transform.rotation);
        cameraTarget = true;
        inventory.character.SetBool("Knight1", true);
        yield return new WaitForSeconds(4f);
        Destroy(this.gameObject);
    }

    IEnumerator Wizard()
    {
        Instantiate(characterWizard, transform.position, characterWizard.transform.rotation);
        inventory.character.SetBool("Wizard1", true);
        cameraTarget = true;
        yield return new WaitForSeconds(4f);
        Destroy(this.gameObject);
    }
}

Am I not able to animate in a Coroutine?

Null exceptions has nothing to do with coroutines, it means something has no value.
In this case, your inventory has no value. Why? Look at your code. The first time Start is called, it hits your third if statement which triggers your coroutine. When it goes into your coroutine, you tell it to access inventory. At this point inventory is null. It’s not until after the if statement that you assign a value to inventory. Move that line to the top of Start and you should be fine.

1 Like

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

1 Like

omg thank you that worked perfectly, shows how I’m such an amateur lol