Cant get my "Jump" sound to work

This is my code:

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

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;
    public AudioClip jumpsound;
    AudioSource audioSource;


    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
  

    Vector3 velocity;
    bool isGrounded;


    void Start()
    {
        audioSource = GetComponent<AudioSource>();
    }
    // Update is called once per frame
    void Update()
    {
       
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y <0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
            audioSource.PlayOneShot(jumpsound);
            audioSource = GetComponent<AudioSource>();
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

    }
}


But I get these errors? How do I fix it?

You don’t seem to have an AudioSource attached to the object with this script on it. So GetComponent will return null, and then line 50 calls audioSource.PlayOneShot() will be trying to tell “nothing” to play a sound, which causes this error.
(The GetComponent call on the next line is also pointless)

(Sidenote: Your pasted script and screenshot appear to be 2 different things - did you make changes between copying the script and taking the screenshot? The error points to line 46 which is blank.)

2 Likes

The very instant you ever see a nullref, the answer is ALWAYS the same:

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.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.