- Home /
play sound only once on SetActive of GameObject
hello, i have looked up and down and tried various scripts, but i cannot seem to get audio to play only once on each time the object is SetActive. i have tried variations of playOneShot etc, but cannot get it to play audio 'once' each time the object is setactive. The particular gameobject randomly switches SetActive true/false. i would like the audio to play once each time the gameobject is setactive.(true). Hope this makes sense, any leads would be greatly appreciated :)
Answer by Stratosome · Jul 15, 2018 at 07:45 AM
Hrmmm, well, assuming that it isn't the audio itself you are having trouble with, and PlayOneShot is making a sound, you could put that audio function inside of the OnEnable() function. Anything inside of that function will happen once every time the object is enabled. There is also a OnDisable() function in case it is useful.
Answer by Kawalyn · Jul 15, 2018 at 10:31 AM
I put together a simple script that might help. Hope it makes sense, feel free to ask if youve got another question :)
EDIT: Just to clarify, this script can be attached to an empty gameobject, you then tell the script which gameobject(s) you want to activate/deactivate upon a certain condition.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetActiveScript : MonoBehaviour {
public GameObject objToActivate;
AudioSource attachedAudioSource;
void Start () {
attachedAudioSource = objToActivate.GetComponent<AudioSource>();
}
void Update () {
// on left mouse button (by default)
if (Input.GetButtonDown("Fire1"))
{
// check if object is active and if audio is playing
if (objToActivate.activeSelf && !attachedAudioSource.isPlaying)
{
// deactivate object
objToActivate.SetActive(false);
}
// check if object is deactivated
else if (!objToActivate.activeSelf)
{
// activate object if it was deactivated
objToActivate.SetActive(true);
// make sure audiosource isnt playing already for some reason
if (!attachedAudioSource.isPlaying)
{
// make sure audio is not looping
attachedAudioSource.loop = false;
// play audiosource
attachedAudioSource.Play();
}
}
}
}
}
@$$anonymous$$awalyn thanks so much for the script, i'll be sure to implement it for my little sound game i am making. Being a creative i don't know too much about scripting, but i was able to use the OnEnable function for this occasion. $$anonymous$$uch appreciated. Thankyou.
Youre welcome^^ Totally forgot about the OnEnable function, way easier i guess. Good luck with your sound game!
Your answer
Follow this Question
Related Questions
master background music toggle not working after changing scenes 1 Answer
Making a sound play only once with a Boolean variable in javascript 1 Answer
audio.Play(); not working while audio.Stop(); works fine when the audio is played on awake 1 Answer
How to determine which audiosource to play from when I'm using two at once. 1 Answer