Play sound when object is visible by the camera

Hello,

I am trying to play a sound when my character enters the camera view and to stop whenever the character exits the view.

So far I have tried to add a box collider with istrigger activated and playing the sound with an audiosource attached to it, but no success.

Lately I have been trying with this very basic script but it is not working. As you can already imagine, I am a completely beginner and quite lost, any help is much appreciated.

using UnityEngine;

public class ObjectVisibilitySoundManager : MonoBehaviour
{
    public AudioSource audioSource; 

    void Start()
    {
        audioSource = GetComponent<AudioSource>(); 
        audioSource.Play(); 
    }

    void OnBecameVisible()
    {
      
        audioSource.enabled = true;
    }

    void OnBecameInvisible()
    {

        audioSource.enabled = false;
    }
}

Thanks

You probably want something like this
(PS : you can also use audioSource.Pause() and audioSource.UnPause() if you don’t want to restart everytime)
Also one important note about the visibility callbacks : (quoted from the forum)

OnBecameVisible and OnBecameInvisible are tricky because they use all cameras in the editor, including the scene editing camera. So make sure the scene view is hidden, or the scene view camera is facing away from the actual scene, or the functions won’t appear to work.

using UnityEngine;

public class ObjectVisibilitySoundManager : MonoBehaviour
{
    public AudioSource audioSource; 

    void Start()
    {
        audioSource = GetComponent<AudioSource>(); 
    }

    void OnBecameVisible()
    {
         audioSource.Play(); 
    }

    void OnBecameInvisible()
    {
       audioSource.Stop();
    }
}

Try to call audioSource.Play and Stop by some other means, or add a Debug.Log there. Find out whether it’s the audio or the visibility part not working.

Did you place the script on a gameObject with renderer?