Search Unity

Why no sound?

Discussion in '2D' started by Theo339, Jan 26, 2020.

  1. Theo339

    Theo339

    Joined:
    Jan 26, 2020
    Posts:
    3
    Hi im new in Unity but i was very Long a c# developer but i have a Problem with the Sound. I want that Unity Play a Sound on collision the collision is working but no Sound.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    [RequireComponent(typeof(AudioSource))]
    public class Collideing : MonoBehaviour
    {
    public AudioClip collisionSound;
    AudioSource audiosource;


    private void OnCollisionEnter2D(Collision2D collision)
    {
    audiosource = GetComponent<AudioSource>();
    if (collision.relativeVelocity.y <= 0f);
    {


    Rigidbody2D rb = collision.collider.GetComponent<Rigidbody2D>();
    if (rb != null)
    {
    audiosource.PlayOneShot(collisionSound, 0.7f);
    Destroy(gameObject);

    Destroy(this);


    }
    }

    }

    }
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Please use code tags when you are posting code to the forums, it becomes much easier to read.

    I can see that you're destroying your game object right after playing the clip. This gameobject contains your AudioSource component, so by destroying the gameobject you're also destroying the audio source, as well as "this" component (that second Destroy is redundant).

    An easy way to delay destruction is to pass a time value in seconds to the Destroy function as a second parameter.
    Destroy(gameObject, collisionSound.length);
     
    eses likes this.
  3. Theo339

    Theo339

    Joined:
    Jan 26, 2020
    Posts:
    3
    Thank you i try it :D