Script acts differently, in rare ocassions

I don’t know why, but sometimes, when my character dies, or I switch scene. I get the following error:

NullReferenceException: Object reference not set to an instance of an object
AnimalContainer.Animal1Update () (at Assets/Scripts/AnimalContainer.cs:46)
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:48)

I’ll give you a look at some of my code:

PlayerController:

private AnimalContainer ac;
void Start()
{
ac = gameObject.AddComponent<AnimalContainer>();
}
	void Update () 
	{
		//Apply animals UpdateFunctions
		switch (shape)
		{
		case 1:
			ac.Animal1Update(); //This line makes an error
			break;
		}

AnimalContainer

public IAnimalFunctions a1;
	void Start () {

		if (Application.loadedLevelName == "LevelOne")
		{

			a1 = gameObject.AddComponent<SheepFunctions>();

		}

		if (Application.loadedLevelName == "LevelTwo")
		{
			a1 = gameObject.AddComponent<SheepFunctions>();
		}

		Animal1Shape();
	}

	public void Animal1Shape()
	{
		a1.ChangeShape();
	}

	public void Animal1Update()
	{
		a1.UpdateFunctions();//This is the line that will give an error
	}

	public void Animal1Ability()
	{
		a1.Ability();
	}

And then there is this last script. Not sure if there’s a problem here, but have a look please:

SheepFunctions

    public class SheepFunctions : MonoBehaviour, IAnimalFunctions {

	private PlayerController player;

	void Start () {
		player = GameObject.Find("Stickman").GetComponent<PlayerController>();
	}

	public void ChangeShape()
	{
		rigidbody2D.gravityScale = 1f;
	}

	public void UpdateFunctions()
	{

	}

	public void Ability()
	{
		if (player.CheckOnGround())
		{
			rigidbody2D.AddForce(Vector2.up * 270f);
		}
	}

}

And one more thing. The game pauses when the error appears. If I hit resume, the game will continue normally without any bugs.

What can be causing this problem? My guess is that sometimes it might do the calls between the different scripts before they are actually added to the gameobject as component. I have heard something about “threads” before, if that was the name. And that might be able to solve the problem, if that’s the case?

Try creating the component in Awake() instead:

void Awake()
{
    ac = gameObject.AddComponent<AnimalContainer>();
}

See if that helps.

The problem seems to be what I had expected. I fixed this by moving this line:

ac = gameObject.AddComponent();

To the Awake () function, instead of Start()