- Home /
Need UI Canvas to appear AFTER audio finishes on trigger
Hi there,
I have a Sound Trigger set up so that when the player enters the audio will play once. What I cant figure out is how to make a canvas I have with buttons appear AFTER the audio finishes. The canvas has buttons that when selected will trigger more audio and I do not want the user to press the button until the triggered audio completes. Below is the code I have so far:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class AudioTrigger : MonoBehaviour { public AudioClip audclip; public bool havePlayed = false; void Start()
{
havePlayed = false;
GetComponent<AudioSource>().playOnAwake = false;
GetComponent<AudioSource>().clip = audclip;
}
void OnTriggerEnter(Collider whoCollidedWithMe) //Plays Sound whenever collision detected
{
if (!havePlayed) // !havePlayed is the same as havePlayed==false
{
// we haven't played yet, but someone collided with us. Who is it ?
if (whoCollidedWithMe.gameObject.tag == "Player")
{
GetComponent<AudioSource>().PlayOneShot(audclip);
Debug.LogWarning("are u working");
havePlayed = true; // we played, so never again
}
else
{
// not the player, so do nothing
}
}
}
}
Answer by Vega4Life · Nov 26, 2018 at 09:24 PM
What you could do is Invoke a method with the length of the audio clip, so something like this:
Invoke("EnableCanvas", audclip.length);
The invoke will call a method named EnableCanvas (that deals with enabling it) with a delay for as long as the clip. Just put this under your playOneShot(audclip);
It could also be a coroutine - StartCoroutine(EnableCanvas(audclip.length);
Then have the yield the length of the clip. yield return newWaitForSeconds(length);
Answer by ughdeeb · Nov 26, 2018 at 09:45 PM
Hi @Vega4Life! Thanks for your help.
I am really new to coding, could you provide more detail for the Coroutine route? Not sure where to put that in the script :/
Thanks
Here is something quick and dirty. It uses a coroutine with a reference to the canvas. Everything with //** is what I added:
//** Reference your Canvas
[SerializeField] Canvas uiCanvas;
void OnTriggerEnter(Collider whoCollidedWith$$anonymous$$e) //Plays Sound whenever collision detected
{
if (!havePlayed) // !havePlayed is the same as havePlayed==false
{
// we haven't played yet, but someone collided with us. Who is it ?
if (whoCollidedWith$$anonymous$$e.gameObject.tag == "Player")
{
GetComponent<AudioSource>().PlayOneShot(audclip);
//** Send clip timer to coroutine \\**
StartCoroutine(EnableCanvas(audclip.length));
uiCanvas.enabled = false;
// ** \\
Debug.LogWarning("are u working");
havePlayed = true; // we played, so never again
}
else
{
// not the player, so do nothing
}
}
}
//** Coroutine that will wait x amount of timer before executing
IEnumerator EnableCanvas(float timer)
{
yield return new WaitForSeconds(timer);
uiCanvas.enabled = true;
}