<aside> 📄 This script plays an AudioClip when the player is looking in its direction, with a volume fade out when looking away.

</aside>

using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class FocusBasedAudio : MonoBehaviour
{
    [Tooltip("Transform of the player's head (camera)")]
    public Transform playerHead;

    [Tooltip("Max angle (degrees) at which volume is audible (0 = directly looking, 180 = silent)")]
    [Range(0f, 180f)]
    public float maxAudibleAngle = 180f;

    private AudioSource audioSource;

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

        // Make sure the audio loops and plays on start
        audioSource.loop = true;
        audioSource.Play();
    }

    void Update()
    {
        if (playerHead == null) return;

        // Vector from player head to sound source
        Vector3 toSound = (transform.position - playerHead.position).normalized;

        // Player head forward vector (where the player is looking)
        Vector3 headForward = playerHead.forward;

        // Calculate angle between head forward and direction to sound (0-180 degrees)
        float angle = Vector3.Angle(headForward, toSound);

        // Volume calculation:
        // volume = 1 when angle = 0
        // volume = 0 when angle >= maxAudibleAngle (usually 180)
        float volume = Mathf.Clamp01(1f - (angle / maxAudibleAngle));

        audioSource.volume = volume;
    }
}