Why does this code results in a Null Reference Error?

Hi! I’m making a script that will play a random sound-effect from an array with no repetition. I struggle with making this work, instead of playing sound-effects it’s giving me Null Reference Errors. The sound should play when you chop a tree (it’s a Unity 3D lumberjack game). The ‘PlayRandomChopSound()’ is called (I debugged), but gives the error instead of sound. The error says the problem is in ‘PlayRandomChopSound()’. I filled the array with the different audioclips in the inspector.
I would really appreciate help :slight_smile:

Here is my code:

 public GameObject player;

    // Axe related code
    public bool axeEquipped = false;
    private float hitRange = 3f;

    // Tree
    private GameObject treeTarget;

    // Tree HP
    private int treeHealth = 100;
    private int damagePerHit = 25;

    // Audio
    private AudioSource ac;
    public AudioClip[] axeSoundArray;
    private int clipIndex;

    private void Start()
        AudioSource ac = player.GetComponent<AudioSource>();

    void Update()
        // Equip axe
        if (Input.GetKeyDown(KeyCode.Alpha1))
            Debug.Log("Axe equipped");
            axeEquipped = true;

        var ray = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));

        if (Input.GetKeyDown(KeyCode.Mouse0) && axeEquipped)
            if (Physics.Raycast(ray, out var hitInfo, hitRange))
                if (hitInfo.collider.CompareTag("Tree"))
                    //treeTarget = hitInfo.collider.gameObject;
                    treeTarget = hitInfo.collider.gameObject;

        if (treeHealth <= 0)
            // Sets tree back to full HP
            treeHealth = 100;

    void DamageTree()
        // Tree loses HP
        treeHealth -= damagePerHit;
        Debug.Log("Tree damage");

        // Axe hit sounds

    void PlayRandomChopSound()
        // Plays a random sound from the array without repetition
        clipIndex = RepeatCheck(clipIndex, axeSoundArray.Length);

    // Avoiding sound repetition
    int RepeatCheck(int previousIndex, int range)
        int index = Random.Range(0, range);

        while (index == previousIndex)
            index = Random.Range(0, range);
        return index;

In Start(), where you think that you’re storing the AudioSource component reference in the previously declared ac, you’re not! Really.

Using AudioSource ac = ... in that method will assign it to a local (to Start()) variable. You don’t want that, right?

Remove AudioSource from Start() and everything should be hunky-dory. Is that one word?