- Home /
trouble playing sound on collision
My character has a grenade that explodes on collision. I'm having some trouble getting my explosion sound to play after the grenade explodes. Any advice?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class grenade : MonoBehaviour
{
private AudioSource explosionSound1;
public int damage = 40;
public float Speed = 4;
public Vector3 LaunchOffset;
public bool Thrown;
public GameObject explosion;
// Start is called before the first frame update
private void Start()
{
explosionSound1 = GetComponent<AudioSource>();
//player = playerObject.GetComponent<player_character>();
if (Thrown) { //if (Thrown && player.transform.localScale.x == 50)
var direction = transform.right + Vector3.up;
GetComponent<Rigidbody2D>().AddForce(direction * Speed, ForceMode2D.Impulse);
Destroy(gameObject, 5); // destroys in 5 seconds
}
transform.Translate(LaunchOffset);
}
// Update is called once per frame
void Update()
{
if (!Thrown) {
transform.position += -transform.right * Speed * Time.deltaTime;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
var enemy = collision.collider.GetComponent<enemy_drone_1>();
if (enemy)
{
//explosionSound1.Play();
enemy.TakeDamage(damage);
explosionSound1.PlayOneShot(explosionSound1.clip);
}
Instantiate(explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
}
Not really an answer but a couple of basic things that I often forget...
Is OnCollisionEnter2D called? Can you put a Debug.Log statement in it?
Is there an AudioListener (usually the Camera) close enough to the AudioSource?
Answer by rh_galaxy · Sep 23, 2021 at 08:48 AM
Try this. here is a sound that play when a bullet hits my ship,
public AudioClip oClipHit; //<- declared to an auduo clip in the inspector
AudioSource oAudioSource; //declared in the beginning (on top of the class)
oAudioSource = GetComponent<AudioSource>(); //declared before using it (in Start())
oAudioSource.PlayOneShot(oClipHit); //declared where the sound would play
I tried that as well but no luck. Is your script attached to your bullet or is it attached to something else? Most of the scripts that I see look like yours but its not working for me...
Your answer
Follow this Question
Related Questions
Dice roll collision sound 1 Answer
How to get sound to play on barrel Explosion 1 Answer
Sound plays even though on awake is unticked 1 Answer
Making a sound using collisions 1 Answer
Collide sound 2 Answers