Cannot figure out error NullReferenceException: Object reference not set to an instance of an object

Following in the well worn footsteps of the first example (in C#) on this page, I created a script called Player.cs attached to an empty GameObject. I declare a List object called ‘Gain’ and in the Start function puts the value ‘3’ into it …

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

public class Player : MonoBehaviour
    public List<int> Gain = new List<int>();

    // Use this for initialization
    void Start ()

I created another script to access Player which contains this code …

 Player player = GetComponent<Player>();
        if (player == null)

It builds ok but I get “Ouch” instead of “3”.

My strategy with Awake and start is generally to do initialize everything specific to an object in its Awake function; and anything that requires knowledge of another object in its Start function.

So in Player, set Gain.Add(3) in your Awake() function

and your other code, check for Gain[0] in either a Start() function (or a function that gets called after Start).

Also, check that your Player object is active - if not, the Start function would not have got called yet.

If you can attach a debugger, put breakpoints on both the lines and see which gets called first. (or use Debug.Log statements).