2025-05-18 03:13:58 +09:00

99 lines
3.1 KiB
C#

namespace UnluckSoftware
{
using UnityEngine;
using System.Collections;
public class ParticleSystemSound :MonoBehaviour
{
public AudioClip[] _shootSound;
public float _shootPitchMin = 0.75f;
public float _shootPitchMax = 1.25f;
public float _shootVolumeMin = 0.25f;
public float _shootVolumeMax = 0.75f;
public AudioClip[] _explosionSound;
public float _explosionPitchMin = 0.75f;
public float _explosionPitchMax = 1.25f;
public float _explosionVolumeMin = 0.25f;
public float _explosionVolumeMax = 0.75f;
public AudioClip[] _crackleSound;
public float _crackleDelay = .25f;
public int _crackleMultiplier = 3;
public float _cracklePitchMin = 0.75f;
public float _cracklePitchMax = 1.25f;
public float _crackleVolumeMin = 0.25f;
public float _crackleVolumeMax = 0.75f;
ParticleSystem.Particle[] _particles;
ParticleSystem _particleSystem;
bool explodeSoundEnabled = true;
bool shootSoundEnabled = true;
private void Start()
{
_particleSystem = GetComponent<ParticleSystem>();
if (SoundController.instance == null)
{
GameObject sc;
sc = new GameObject();
sc.AddComponent<SoundController>();
sc.name = "Unluck Software Sound Controller";
}
}
private void LateUpdate()
{
if (_particles == null || _particles.Length < _particleSystem.main.maxParticles)
{
_particles = new ParticleSystem.Particle[_particleSystem.main.maxParticles];
}
int length = _particleSystem.GetParticles(_particles);
int i = 0;
while (i < length)
{
if (explodeSoundEnabled && _explosionSound.Length > 0 && _particles[i].remainingLifetime < Time.deltaTime * 3f)
{
explodeSoundEnabled = false;
Invoke("EnableExplode", 0.05f);
int r = UnityEngine.Random.Range(0, _explosionSound.Length);
SoundController.instance.Play(_explosionSound[r], UnityEngine.Random.Range(_explosionVolumeMax, _explosionVolumeMin), UnityEngine.Random.Range(_explosionPitchMin, _explosionPitchMax), _particles[i].position);
if (_crackleSound.Length > 0)
{
for (int j = 0; j < _crackleMultiplier; j++)
{
StartCoroutine(Crackle(_particles[i].position, _crackleDelay + j * .1f));
}
}
}
if (shootSoundEnabled && _shootSound.Length > 0 && _particles[i].remainingLifetime >= _particles[i].startLifetime - Time.deltaTime)
{
shootSoundEnabled = false;
Invoke("EnableShoot", 0.05f);
SoundController.instance.Play(_shootSound[UnityEngine.Random.Range(0, _shootSound.Length)], UnityEngine.Random.Range(_shootVolumeMax, _shootVolumeMin), UnityEngine.Random.Range(_shootPitchMin, _shootPitchMax), _particles[i].position);
}
i++;
}
}
void EnableShoot()
{
shootSoundEnabled = true;
}
void EnableExplode()
{
explodeSoundEnabled = true;
}
public IEnumerator Crackle(Vector3 pos, float delay)
{
yield return new WaitForSeconds(delay);
SoundController.instance.Play(_crackleSound[UnityEngine.Random.Range(0, _crackleSound.Length)], UnityEngine.Random.Range(_crackleVolumeMax, _crackleVolumeMin), UnityEngine.Random.Range(_cracklePitchMax, _cracklePitchMin), pos);
}
}
}