- Home /
Sound plays right at the beginning
Hello! So, I wanted to check if my bullet hit the head of the enemy and wanted to play a headshotsound if that was the case, so I wrote this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class HitSounds : MonoBehaviour {
public AudioClip headshotSound;
// Use this for initialization
new AudioSource audio;
void Start () {
audio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Head")
{
audio.PlayOneShot(headshotSound, 0.2F);
}
}
}
Now, my problem is that everytime i start my game, the sound immediately plays. Sorry if the answer is obvious, Im new to sounds in Unity. Instructions on how to fix my issue are more than enough! Answers in code are appreciated but not expected.
Answer by nomadic · Jun 18, 2018 at 06:54 PM
On your AudioSource, make sure that Play On Awake is disabled.
https://docs.unity3d.com/Manual/class-AudioSource.html https://docs.unity3d.com/ScriptReference/AudioSource-playOnAwake.html
Answer by tormentoarmagedoom · Jun 18, 2018 at 06:57 PM
Good day.
This is because the Clip or Audiosource have active the option "Play on awake".
Anyway, i recoomend you, to dont have this object active in the scene. Is better if you have it as prefab, and instantiate it when a headshot is done, and destroy it after 1, 2 or 3 seconds.
this way, if 2 headshots are done ione right after the other, you will hear 2 headsot sounds correctly.
Bye..
Your answer
Follow this Question
Related Questions
Can't get sound clip from array to play properly 1 Answer
Audio Loops? 1 Answer
OnTriggerExit stop audio 1 Answer
Play sound when enemy chase 1 Answer
How to play "audiosource" component in a prefab from script? 0 Answers