using System.Diagnostics; using System.Linq; using UnityEngine; using System.Collections; using Debug = UnityEngine.Debug; public class AiSound : MonoBehaviour { public AudioSource audio; private bool _isPlaying; private float _startTime; public float rangeScale = 1.0f; public float StartTime { get { return _startTime; } } public bool IsPlaying { get { return _isPlaying; } } void Start () { } private void BroadcastBeginPlaying() { _startTime = Time.time; var overlapped = Physics2D.OverlapCircleAll(transform.position, audio.maxDistance * rangeScale); var listeners = overlapped.Select(v => v.gameObject.GetComponent()).Where(v => v != null).Distinct().ToList(); if (listeners.Count() != 0) { foreach (var listener in listeners) { listener.OnSoundStart(this); Debug.Log("Broadcast begin playing to object: " + listener.name); } } else { Debug.Log("AiSound started but no listeners found"); } } private void BroadcastEndPlaying() { Debug.Log("EndPlaying"); } void Update () { if (audio != null) { if (_isPlaying != audio.isPlaying) { if (!_isPlaying) { BroadcastBeginPlaying(); } else { BroadcastEndPlaying(); } } _isPlaying = audio.isPlaying; } else { Debug.LogWarning("AiSound AudioSource is null!!!", this); } } void OnDrawGizmos() { if (audio != null) { AdvancedGizmo.DrawCircle(transform.position, Vector3.forward, audio.maxDistance * rangeScale, Color.green); } } }