Playing Audio?

I am having troubles playing audio files during specific events.

First, I want the game to play an audioclip once the player is dead. This is the script (attached to an empty GameObject):

`

private PlayerHealth player;
bool dead = false;
AudioClip myaudio;

void Start () {
player = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
}

void Update (){
	dead = player.playerDead;
	if (dead){
		PlayStuff();	
	}
}

void PlayStuff () {
	
	print ("Player is dead, play audio.");
		audio.Play();
	
}`

I have tested this and the function runs when it should, but nothing plays. The aforementioned game object to which this script is attached has an Audio Source component with the desired audio clip.

Another goal is for an audio clip to be played by my enemies when they are in a certain radius of the player. I have not tried to accomplish this task as I expect I would run into the same problem.

It would be much appreciated if anyone could shed some light on this topic and give me a hand.

1 Answer

1

Well, it’s very simple, you need to have a Variable that referennces to the AudioClip you want. these Variables are called AudioClip.
to play them, just use: audio.PlayOneShot(variable);

It seems that you do have the variable, but you need to assign it in the Inspector window, and then change that line to make the Audio play :slight_smile:
Also, make sure to have an AudioSource attached to the object that will recieve this Script!

Well, about your second question, there’s multiple solutions to this, basically, what you could do is, have a Vector3 for the enemy, and then, to calculate the distance between them, you use Vector3.distance(player location,enemy location).

This will give you a float, and that’s the distance between the two positions, you can then use this float to make your conditions and stuff.

Other way to do that, is to have a big collider around the player, set it to Trigger, and then, in the Enemy script, you create a “OnTriggerEnter” function and then you do your stuff there.
Your choice mate :slight_smile:

For more info on those topics:

OnTriggerEnter:Unity - Scripting API: Collider.OnTriggerEnter(Collider)

Vector3.distance:Unity - Scripting API: Vector3.Distance

Audio: audio.Play does not work - Unity Answers