I am trying to get this voice recording to play however the following message is appearing. I am a newbie so any help would be appreciated. it says the error is on line 36 Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Playsound : MonoBehaviour { GameObject BPlay, BStop; // Start is called before the first frame update void Start() { BPlay = GameObject.Find("Play"); BStop = GameObject.Find("Stop"); BPlay.SetActive(true); BStop.SetActive(false); } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.tag == "Play") { BPlay.SetActive(false); BStop.SetActive(true); BPlay.GetComponent<AudioSource>().Play(); } if (hit.collider.tag == "Stop") { BPlay.SetActive(true); BStop.SetActive(false); BPlay.GetComponent<AudioSource>().Stop(); } } }
First thing to do is restructure your code. Don't use GetComponent in Update, because that will waste performance. Cache a reference to the audio component in a class level variable, and then manually set that variable at design time or use GetComponent in the Start or Awake function. Beyond that, does the BPlay game object definitely have an audio component, and is that audio component enabled? Next, since you are disabling the BPlay game object sometimes, it is possible that your BPlay game object is currently disabled when you are trying to access it's audio component.
Wrong forum (use scripting) but you are deactivating the GameObject right before you try to play its AudioSource. Put the audio on a different game object, or disable the button/sprite instead of deactivating the GO.
thank you both for the help The error has been however it does not play the sound thank you i am trying to fix it no luck at the moment very new at coding. how do I set disable the sprite what code do need to added