Okay, so I am making a basic 2D tower defense game, and I’m just wanting my goblin to make gobliny laughing sounds as he approaches the tower, and then make attacky sounds when he gets there, so the goblin has a small box collider for front detection, and he has 2 game objects: one called LaughSounds, and one called AttackSounds. They each have an AudioSource component as well as a script called RandomSoundPlayer that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSoundPlayer : MonoBehaviour {
private AudioSource audioSource;
[SerializeField]
private List<AudioClip> soundClips = new List<AudioClip>();
[SerializeField]
private float soundTimerDelay;
private float soundTimer;
public float lowPitchRange; //The lowest a sound effect will be randomly pitched.
public float highPitchRange; //The highest a sound effect will be randomly pitched.
// Use this for initialization
void Awake () {
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
//Increment timer to count up to restarting.
soundTimer = soundTimer + Time.deltaTime;
//If the timer reaches the delay...
if (soundTimer >= soundTimerDelay) {
//...reset timer.
soundTimer = 0f;
//Choose a random pitch to play back clip at between high and low pitch ranges.
float randomPitch = Random.Range (lowPitchRange, highPitchRange);
//Set the pitch of the audio source to the randomly chosen pitch.
audioSource.pitch = randomPitch;
// ...choose a random sound.
AudioClip randomSound = soundClips [Random.Range (0, soundClips.Count)];
// Play the sound.
audioSource.PlayOneShot (randomSound);
}
}
}
Then there’s the part of the enemy movement script that deals with enabling and disabling the LaughSounds and AttackSounds game objects on the goblin at the appropriate times. I tried to make it as simple as possible for right now, and here’s how it looks:
void OnTriggerStay2D (Collider2D other)
{
if (other.gameObject.tag == "Wall") {
animator.SetBool ("frontClear", false);
laughSounds.SetActive (false);
attackSounds.SetActive (true);
} else {
if (other.gameObject.tag == "Tower") {
animator.SetBool ("frontClear", false);
laughSounds.SetActive (false);
attackSounds.SetActive (true);
} else {
animator.SetBool("frontClear", true);
attackSounds.SetActive (false);
laughSounds.SetActive (true);
}
}
}
finally, in the inspector, I dropped all the sounds needed:
SO, what happens is, when the goblin starts, he starts laughing randomly as he should. Then as soon as he reaches the tower, the LaughSounds object goes inactive as it should and the AttackSounds object becomes active as it should. HOWEVER, at that point, the attack sounds aren’t playing properly. I have done some tests, and script is activating, the timer is working properly, but the sounds are making a really short blip for about 1/10 of a second and then cutting off. Sometimes you can’t hear anything.
Anyone know why??? D: