Search Unity

Audio To Script help?

Discussion in 'Scripting' started by Luke3671, Mar 7, 2017.

  1. Luke3671

    Luke3671

    Joined:
    Jul 6, 2014
    Posts:
    56
    Hello Unity,
    I'm learning to code in JS (I know its not the best but its a good start) I'm having an issue adding audio to my game-object or will i have to make an audio script on its own & add it to an empty & place that by the object that's getting destroyed? As of right now the object gets destroyed right away then particle get remove 4 seconds after when player hits said object. Script i'm using is below; (This is health for the objects)

    Code (JavaScript):
    1. // This section is health for the object when hits 0 its destroys itself.
    2. var health :int = 8;
    3.  
    4. function Damage(damage:int){
    5.     health -= damage;
    6.     if(health <= 0)Destroy(gameObject);
    7. }
    8.  
    9.     // This section is for effect to play when object is destroyed.
    10.     var explosion: GameObject;
    11.  
    12.     function OnCollisionEnter(){
    13.         var expl = Instantiate(explosion, transform.position, Quaternion.identity);
    14.         Destroy(gameObject);
    15.         Destroy(expl, 4); // Deletes the effect after 4 seconds of when object is destroyed.
    16.     }
    17.  
    18.     // This section is Sound (Not working)
    19.     var reload : AudioClip;
    Thank you if anyone can help me today
    Luke
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,447
    Can use this (it plays even after gameobject gets destroyed)
    https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html

    or other alternatives,
    - disable the gameobjects renderer/collider/etc, instead of destroying, so it has time to play sound, before its destroyed (add delay to Destroy(gameObject, x))
    - or add sound into the particlesystem prefab, and have [x] play on awake, so it plays automatically when particle system gets instantiated