Sound problems. PLAY () and Destroy (gameObject) in Unity

I made a script for my star to give 1 point, make a particle, play a sound, and destroy an object. Everything works fine, but now the script is waiting for the sound to stop playing. What method do you suggest to destroy the object before playing the sound? I can make a new collection of audio gameobjects, attach it to the star group and cause it to play like I did with the particle system, or is there a better way to do this?

using UnityEngine;
using System.Collections;


public class Star : MonoBehaviour {

    public ParticleSystem StarParticle;

    public AudioClip otherClip;

    IEnumerator OnTriggerEnter (Collider player)
    { 
        ScoreManager.score += 1;


        StarParticle.Play ();

        AudioSource audio = GetComponent<AudioSource>();
        audio.Play();
        yield return new WaitForSeconds(audio.clip.length);

        Destroy (gameObject);

    }
}

      

What a code.

+3


source to share


2 answers


From reading the comments, how about this:

Take the value audio.clip.length

into a variable and decrease it, for example, divide by 2 or 4, etc. so that the script continues 50% or 25% through the audio file playback.



 IEnumerator OnTriggerEnter (Collider player)
{ 
    ScoreManager.score += 1;


    StarParticle.Play ();

    AudioSource audio = GetComponent<AudioSource>();

    waitValue = (audio.clip.length/2);
    audio.Play();
    yield return new WaitForSeconds(waitValue);

    Destroy (gameObject);

    }

      

+2


source


This is the solution to my problem. I disable the collider (to prevent the other ppl from getting points from that star) and the grid (to make the star invisible) and then after replay I destroy my star gameObject. thanks for the answers!

using UnityEngine; using System.Collections;

public class Star: MonoBehaviour {



public ParticleSystem StarParticle;

IEnumerator OnTriggerEnter (Collider player)
{ 
    ScoreManager.score += 1;


    StarParticle.Play ();

    AudioSource audio = GetComponent<AudioSource>();
    audio.Play();
    GetComponent<Collider>().enabled = false;
    GetComponent<MeshRenderer>().enabled = false;
    yield return new WaitForSeconds(audio.clip.length);

    Destroy (gameObject);

}

      

}

+1


source







All Articles