I am working on a game and I am trying to add a sound effect.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerbody;
private Animator playerAnim;
private bool grounded;
public bool gameover;
public float jumpforce;
public float gravmod;
public ParticleSystem explosion;
public ParticleSystem dirt;
public AudioClip jumpSound;
public AudioClip crashSound;
private AudioSource playerAudio;
// Start is called before the first frame update
void Start()
{
playerbody = GetComponent<Rigidbody>();
playerAnim = GetComponent<Animator>();
playerAudio = GetComponent<AudioSource>();
Physics.gravity *= gravmod;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && grounded && gameover == false)
{
playerAudio.PlayOneShot(jumpSound, 1.0f);
playerbody.AddForce(Vector3.up * jumpforce, ForceMode.Impulse);
playerAnim.SetTrigger("Jump_trig");
grounded = false;
dirt.Stop();
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
grounded = true;
dirt.Play();
}
if (collision.gameObject.CompareTag("Obstacle"))
{
playerAudio.PlayOneShot(crashSound, 1.0f);
gameover = true;
playerAnim.SetBool("Death_b", true);
playerAnim.SetInteger("DeathType_int", 1);
explosion.Play();
dirt.Stop();
}
}
}
At playerAudio.PlayOneShot
, it just won't play and the rest of that part of the code stops working. It returns ArgumentNullException: Value cannot be null
even though jumpSound
and crashSound
are both clearly defined. What is wrong?
jumpSound
&crashSound
are defined, but it doesn't look like either of them has been initialized anywhere in the code. How are you setting their values (or put differently, how are you indicating what sound/file/resource they correspond to)? \$\endgroup\$