What I would like to do is Have a sound play everytime a particle is emitted in Unity. I will Preface this by saying I am very new to Coding in General but I can usually figure things out. What I have for code so far is:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tower : MonoBehaviour
{
[SerializeField] Transform objectToPan = null;
[SerializeField] float attackRange = 10f;
[SerializeField] ParticleSystem projectileParticle = null;
ParticleSystem TurretGun;
Transform targetEnemy;
// Update is called once per frame
void Update()
{
SetTargetEnemy();
if (targetEnemy)
{
objectToPan.LookAt(targetEnemy);
FireAtEnemy();
}
else
{
Shoot(false);
}
}
private void SetTargetEnemy()
{
var sceneEnemies = FindObjectsOfType<EnemyDamage>();
if (sceneEnemies.Length == 0) { return; }
Transform closestEnemy = sceneEnemies[0].transform;
foreach (EnemyDamage testEnemy in sceneEnemies)
{
closestEnemy = GetClosest(closestEnemy, testEnemy.transform);
}
targetEnemy = closestEnemy;
}
private Transform GetClosest(Transform transformA, Transform transformB)
{
var distToA = Vector3.Distance(transform.position, transformA.position);
var distToB = Vector3.Distance(transform.position, transformB.position);
if (distToA < distToB)
{
return transformA;
}
return transformB;
}
private void FireAtEnemy()
{
float Distance = Vector3.Distance(targetEnemy.transform.position,
gameObject.transform.position);
if (Distance <= attackRange)
{
Shoot(true);
}
else
{
Shoot(false);
}
}
void OnParticleCollision(ParticleSystem colliderForBirth, AudioSource birthSound)
{
Collider birth = colliderForBirth.GetComponent<Collider>();
if (birth)
{
birthSound = GameObject.Find("TurretGun").GetComponent<AudioSource>();
birthSound.Play();
}
}
private void Shoot(bool isActive)
{
var emissionModule = projectileParticle.emission;
emissionModule.enabled = isActive;
}
}
And when the Gun is firing I want the sound to be I guess basically attached to the Particle being emitted .
Any help would be greatly appreciated.