Hello! I’m using this script to randomly select an audio from a list of 3 and it instantiates it into the game then the sound gets deleted after it finishes playing. The script was working perfectly fine until today when I opened up Unity after about a week or so, whenever the script is run and the audio spawns and is deleted, it creates a New Game Object in the hierarchy and it doesn’t get deleted.
I’m not sure what is creating this New Game Object and I can’t figure out how to get rid of it.
I know it’s the sound part of my script because when I removed this script, New Game Object wasn’t getting created.
I’m new to coding and I’m just following lots of tutorials to find scripts that work so if there’s a better way to make this script then please let me know!
public void PlaySound ()
GameObject sound = new GameObject (); sound.transform.position = transform.position; int randomClip = Random.Range (0, glassSound.Length); Instantiate (glassSound [randomClip], transform.position, transform.rotation); AudioSource audioSource = sound.AddComponent<AudioSource> (); audioSource.PlayOneShot (glassSound [randomClip]); Destroy (audioSource, glassSound [randomClip].length); }