- Home /
AudioSource.PlayClipAtPoint creating unlimited AudioOneShot
I recently made a script where when a player place a fuse in a fusebox, the generator will be active. When said thing happen, the generator will play a looped sound.
Instead however, the generator do play the sound but it created unlimited AudioOneShots which anyone can guess, is bad. Below are the coding.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Generator : MonoBehaviour {
public bool GeneratorOn;
public AudioClip GeneratorOnSound;
// Use this for initialization
void Start ()
{
GeneratorOn = false;
}
// Update is called once per frame
void Update ()
{
if (Fusebox.FuseOn == true)
{
GeneratorOn = true;
AudioSource.PlayClipAtPoint (GeneratorOnSound, transform.position);
GetComponent<AudioSource>().clip = GeneratorOnSound;
GetComponent<AudioSource>().Play();
}
//if (GeneratorOn == true)
//{
//AudioSource.PlayClipAtPoint (GeneratorOnSound, transform.position);
//GetComponent<AudioSource>().clip = GeneratorOnSound;
//GetComponent<AudioSource>().Play();
//}
}
}
Any help will be very appreciated.
Answer by UnityCoach · Jan 06, 2017 at 01:15 PM
Update is called every frame. You need to "trigger" the audio playback when a condition is met, and put this condition back to false right after.
There are many ways you can do this, using Coroutine, waiting for the sound to complete and set the value back to false, and so on. I would advise to use a property though. Like :
private bool _generatorOn;
public bool GeneratorOn
{
get { return _generatorOn; }
set
{
if (_generatorOn != value) // make sure the value changed
{
_generatorOn = value; // assign the new value;
if (_generatorOn)
AudioSource.PlayClipAtPoint (GeneratorOnSound, transform.position); // play only if the value is now true
}
}
}
Then, in your Update method, simply do :
GeneratorOn = Fusebox.FuseOn;
@UnityCoach Your help is very appreciated, but as it turns out, I managed to create an alternate solution, basically, I make the sound a game object that was disabled at first, then enabled when certain things are met.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Generator : $$anonymous$$onoBehaviour {
public bool GeneratorOn;
public GameObject OnSound; //Here
// Use this for initialization
void Start ()
{
GeneratorOn = false;
OnSound.SetActive (false);
}
// Update is called once per frame
void Update ()
{
if (Fusebox.FuseOn == true)
{
GeneratorOn = true;
OnSound.SetActive (true); //And here
}
}
}
This works yes, though using SetActive every frame for "nothing" isn't a practice I would consider.