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 :slight_smile:

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.

I put together a simple script that might help. Hope it makes sense, feel free to ask if youve got another question :slight_smile:


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();
                }                
            }
        }		
	}
}