- Home /
Instantiate script for randomly selecting sound is suddenly creating New Game Object in hierarcy??
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);
}
Answer by mochacchi · Jul 25, 2018 at 06:20 AM
I changed the last line of code to
Destroy (sound, glassSound [randomClip].length);
and it works now! Thanks!!
Answer by dan_wipf · Jul 25, 2018 at 05:55 AM
well you never Destroy the GameObject sound in your Script, which holds your AudioSource and the sound to play.
just swap the line with the Destroy part with
if you want to have your GameObject as a Child of your Script GameObject:Destroy(sound);
public void PlaySound () {
GameObject sound = new GameObject ();
sound.transform.parent = this.transform;
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 (sound);
}
@dan_wipf I tried this script but the sound isn't played when it's supposed to. It doesn't spawn within my scene either.
Your answer
Follow this Question
Related Questions
GetChild(0) returns nonexistent object 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Order of instantiated objects in hierachy 3 Answers
Why is instantiated animator prefabs are not working properly? 2 Answers