94 lines
2.8 KiB
C#
94 lines
2.8 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using Cysharp.Threading.Tasks;
|
|
using UnityEngine;
|
|
using UnityEngine.Pool;
|
|
using System.Linq;
|
|
|
|
namespace BITKit.Sensors
|
|
{
|
|
public interface IAudioObject
|
|
{
|
|
float GetVolume();
|
|
}
|
|
|
|
public class AudioSensor : MonoBehaviour, ISensor
|
|
{
|
|
|
|
[Header(Constant.Header.Settings)] [SerializeField]
|
|
private bool autoUpdate;
|
|
|
|
[SerializeField] private float radius;
|
|
private readonly CacheList<Transform> cache = new();
|
|
private readonly CacheList<AudioSensorService.AudioSensorData> data = new();
|
|
public AudioSensorService.AudioSensorData[] Noises => data.ValueArray;
|
|
private readonly HashSet<int> _addedSet = new();
|
|
|
|
private void OnEnable()
|
|
{
|
|
Id = GetInstanceID();
|
|
SensorQueue.Register(Id, this);
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
SensorQueue.UnRegister(Id);
|
|
}
|
|
|
|
public async UniTask Execute(float delta)
|
|
{
|
|
|
|
AudioSensorService.LockHash.Add(Id);
|
|
|
|
try
|
|
{
|
|
var position = transform.position;
|
|
cache.Clear();
|
|
data.Clear();
|
|
_addedSet.Clear();
|
|
await UniTask.SwitchToTaskPool();
|
|
|
|
AudioSensorService.AudioSensorData[] value;
|
|
|
|
value = AudioSensorService.QuadtreeRoot.Find(new Bounds(position, Vector3.one * radius)).ToArray();
|
|
|
|
for (var index = 0; index < value.Length; index++)
|
|
{
|
|
var x = value[index];
|
|
var distance = Vector3.Distance(position, x.Position);
|
|
if (distance > radius) continue;
|
|
if (Ignores.Contains(x.Id)) continue;
|
|
_addedSet.Add(index);
|
|
// if (x.Transform)
|
|
// cache.Add(x.Transform);
|
|
// data.Add(x);
|
|
}
|
|
|
|
await UniTask.SwitchToMainThread();
|
|
if (destroyCancellationToken.IsCancellationRequested) return;
|
|
foreach (var x in _addedSet)
|
|
{
|
|
if (value[x].Transform)
|
|
cache.Add(value[x].Transform);
|
|
data.Add(value[x]);
|
|
}
|
|
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
BIT4Log.LogException(e);
|
|
}
|
|
|
|
AudioSensorService.LockHash.Remove(Id);
|
|
//return UniTask.CompletedTask;
|
|
}
|
|
|
|
public HashSet<int> Ignores { get; } = new();
|
|
public int Id { get; set; }
|
|
public IEnumerable<Transform> Get() => cache.ValueArray;
|
|
public bool IsValid(Collider _collider) => false;
|
|
public float GetDistance() => radius;
|
|
public bool AutoUpdate => autoUpdate;
|
|
}
|
|
} |