- Home /
Using Time with OnGUI Help
Hello, I am new to Scripting and I ran into a problem.
Here is an example of what I am trying to do:
var clip : AudioClip;
function OnGUI {
if (GUI.Button (Rect (0,0,0,0), "Level 1")) {
audio.PlayOneShot(clip);
// Time Delay
Application.LoadLevel(1);
}
}
Where I put // Time Delay, I needed something to delay Application.LoadLevel(1); from happening yet, so I could hear the full audio clip before loading level 1.
Remember that I am new to scripting.
Thank you everyone :) I hope you can help
Answer by fafase · Apr 14, 2012 at 05:08 PM
As correctly stated by @OrangeLightning you cannot yield a OnGui. So you need a coroutine.
var clip : AudioClip;
var second : float;
function OnGUI (){
if (GUI.Button (Rect (0,0,0,0), "Level 1")) {
audio.PlayOneShot(clip);
Wait();
}
}
function Wait(){
yield WaitForSeconds(second);
Application.LoadLevel(1);
}
This one should work as I use it.
Here is the above code , fixed , tested and working :
var clip : AudioClip;
var second : float = 1.5; // change the time here, or in the inspector
function OnGUI() {
if (GUI.Button (Rect (0,0,100,35), "Level 1")) {
audio.PlayOneShot(clip);
Wait();
}
}
function Wait(){
yield WaitForSeconds(second);
Application.LoadLevel(1);
}
you forgot the parentheses at the GUI function. Also the button had no dimensions
Right for the parenthesis, I edited. The dimensions, it is just coz I copy pasted his codes.
Answer by gregzo · Apr 14, 2012 at 06:18 PM
Hummm, if I were you, I wouldn't use PlayOneShot. Make sure you have an AudioSource Component on your object, set it to playOnAwake = false, loop = false, then the following code will wait the precise time of your clip before launching the next level.
var myClip : AudioClip;
function OnGUI() {
if (GUI.Button (Rect (0,0,100,35), "Level 1")) {
audio.clip = myClip;
audio.Play();
WaitTillClipFinishesAndLoadLevel();
}
}
function WaitTillClipFinishesAndLoadLevel(){
while(audio.isPlaying)
{
yield;
}
Application.LoadLevel(1);
}
P.S.: Audio is my specialty... In case you need help!
Your answer
Follow this Question
Related Questions
Ball throw and brick count 1 Answer
Audio loop after time 2 Answers
Why does the audio sound different than the original ? 0 Answers
Destroying Collected Objects / Playing Audio 2 Answers
Analyzing an audio file. 0 Answers