Weird NullReferenceException

I have never seen a error like this. What causes it and how to fix?

NullReferenceException
Chest+c__Iterator0.MoveNext () (at Assets/Scripts/Items/Chest.cs:51)

using UnityEngine;
using System.Collections;

public class Chest : MonoBehaviour {
	public AnimationClip open;
	public AnimationClip close;

	public enum State {
		open,
		close,
		inbetween
	}

	public State state;

	// Use this for initialization
	void Start () {
		state = Chest.State.close;
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	public void OnMouseEnter() {
		Debug.Log ("Enter");
	}

	public void OnMouseExit() {
		Debug.Log ("Exit");
	}

	public void OnMouseDown() {
		Debug.Log ("Click");
		switch(state) {
		case State.open:
			state = Chest.State.inbetween;
			StartCoroutine("Close");
			break;
		case State.close:
			state = Chest.State.inbetween;
			StartCoroutine("Open");
			break;
		}
	}

	private IEnumerator Open() {
		animation.Play ("open");

		yield return new WaitForSeconds(animation["open"].length);
		state = Chest.State.open;
	}

	private IEnumerator Close() {
		animation.Play ("close");
		
		yield return new WaitForSeconds(animation["close"].length);
		state = Chest.State.close;
	}
}

In line number 51:

 yield return new WaitForSeconds(animation["open"].length);

animation does not have an “open” element or this element is null?

try to rewrite it with constant value:

 yield return new WaitForSeconds(10);

I do have a animation in the gameobject, with the name “open”. Same goes with “close”.

You have defined the two AnimationClip fields open and close in the class. Do you set them in the Inspector to the corresponding animation clips? If so you can use them in the coroutine to wait for the correct time span.

 yield return new WaitForSeconds(open.length);

and

 yield return new WaitForSeconds(close.length);

But make sure that the fields correctly set before.

not sure where the problem is but this error usually indicates that the enumerator gets invalid during enumeration. this happens for example when you enumerate over a collection and then remove an element what makes the enumerator invalid. thats why you should add the objects to delete to another collection and enumerate over this to remove them in the initial collection. but as beeing said i don’t know how this interferes with your animation stuff. so just a note for further investigation.

Changed it to a constant value, but now I am getting a “The animation state open could not be played because it couldn’t be found!”. It is in the same place as close animation, and close animation works fine with the same script.

BUMP