BITKit/Src/Unity/Scripts/Sensor/AudioSensor.cs

94 lines
2.8 KiB
C#
Raw Normal View History

2024-04-16 04:06:46 +08:00
using System;
2023-06-05 19:57:17 +08:00
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Pool;
using System.Linq;
2024-04-16 04:06:46 +08:00
2023-06-05 19:57:17 +08:00
namespace BITKit.Sensors
{
public interface IAudioObject
{
float GetVolume();
}
2024-05-31 01:23:15 +08:00
public class AudioSensor : MonoBehaviour, ISensor
2023-06-05 19:57:17 +08:00
{
2024-05-31 01:23:15 +08:00
[Header(Constant.Header.Settings)] [SerializeField]
private bool autoUpdate;
[SerializeField] private float radius;
2024-04-16 04:06:46 +08:00
private readonly CacheList<Transform> cache = new();
2024-05-31 01:23:15 +08:00
private readonly CacheList<AudioSensorService.AudioSensorData> data = new();
public AudioSensorService.AudioSensorData[] Noises => data.ValueArray;
private readonly HashSet<int> _addedSet = new();
2024-04-16 04:06:46 +08:00
private void OnEnable()
2023-06-05 19:57:17 +08:00
{
2024-04-16 04:06:46 +08:00
Id = GetInstanceID();
2024-05-31 01:23:15 +08:00
SensorQueue.Register(Id, this);
2024-04-16 04:06:46 +08:00
}
2024-05-31 01:23:15 +08:00
2024-04-16 04:06:46 +08:00
private void OnDisable()
{
SensorQueue.UnRegister(Id);
}
2024-05-31 01:23:15 +08:00
public async UniTask Execute(float delta)
2024-04-16 04:06:46 +08:00
{
2024-05-31 01:23:15 +08:00
AudioSensorService.LockHash.Add(Id);
try
2023-06-05 19:57:17 +08:00
{
2024-05-31 01:23:15 +08:00
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]);
}
2023-06-05 19:57:17 +08:00
}
2024-05-31 01:23:15 +08:00
catch (Exception e)
{
BIT4Log.LogException(e);
}
AudioSensorService.LockHash.Remove(Id);
//return UniTask.CompletedTask;
2023-06-05 19:57:17 +08:00
}
2024-05-31 01:23:15 +08:00
public HashSet<int> Ignores { get; } = new();
2024-04-16 04:06:46 +08:00
public int Id { get; set; }
public IEnumerable<Transform> Get() => cache.ValueArray;
public bool IsValid(Collider _collider) => false;
public float GetDistance() => radius;
2024-05-31 01:23:15 +08:00
public bool AutoUpdate => autoUpdate;
2023-06-05 19:57:17 +08:00
}
}