- Home /
Fading out before load script not functioning correctly?
So here is a script i found on the unity forums, and I edited it slightly so it would fade out automatically when loading a level. The script works itself works, but the (if loading level) part i added doesnt work, and now it wont work at all. The objects are not present for some reason when the game loads either. Not sure why, any ideas? Thanks.
enum Fade {In, Out}
var fadeTime = 3;
function Awake () {
DontDestroyOnLoad (transform.gameObject);
}
function Update () {
if (Application.isLoadingLevel){
FadeAudio(fadeTime, Fade.Out);
Destroy (gameObject, 4);
}
}
function FadeAudio (timer : float, fadeType : Fade) {
var start = fadeType == Fade.In? 0.0 : 1.0;
var end = fadeType == Fade.In? 1.0 : 0.0;
var i = 0.0;
var step = 1.0/timer;
while (i <= 1.0) {
i += step * Time.deltaTime;
audio.volume = Mathf.Lerp(start, end, i);
yield;
}
}
var fadeTime always the same value?
may be you lost some thing like "fadeTime++".
Answer by Sajidfarooq · Aug 23, 2013 at 07:45 AM
The problem is, since your code is in "Update", the FadeAudio function is called every frame that Application.isLoadingLevel == true
. i.e, its called many times over, whereas you should be calling it only once.
The solution is to either call this function in "Start", so its called only once, or to manually create a flag that makes sure that FadeAudio
is only called once.
Answer by 3 · Aug 23, 2013 at 08:41 AM
Solved my own problem, the object was a child object, so the whole thing got deleted. Thanks,
Yes it is:
enum Fade {In, Out}
var fadeTime = 2;
function Start () {
//DontDestroyOnLoad(this.gameObject);
DontDestroyOnLoad (transform.gameObject);
if (Application.isLoadingLevel == true){
FadeAudio(fadeTime, Fade.Out);
Destroy (gameObject, 3);
}
}
function Update () {
}
function OnLevelWasLoaded (level : int) {
if (Application.isLoadingLevel == true){
FadeAudio(fadeTime, Fade.Out);
Destroy (gameObject, 3);
}
}
function FadeAudio (timer : float, fadeType : Fade) {
var start = fadeType == Fade.In? 0.0 : 1.0;
var end = fadeType == Fade.In? 1.0 : 0.0;
var i = 0.0;
var step = 1.0/timer;
while (i <= 1.0) {
i += step * Time.deltaTime;
audio.volume = $$anonymous$$athf.Lerp(start, end, i);
yield;
}
}
Looking at your code, no its not. Your Update function is empty! You moved your code to "Start" as I recommended below. Unless you posted the wrong code here...
So your problem was, indeed, that your code was in Update, as I suggested. You can confirm this by returning the code to Update, as you previously had it.
Oh your right, I hadn't even noticed. It was a combo of both issues. I checked off your answer, thanks for the help!
Your answer
Follow this Question
Related Questions
Static objects increasing load time in Unity 5? 2 Answers
Why is my backtrack's volume getting lower? 0 Answers
[Daydream] Disable default volume menu? 0 Answers
How to load multiple wav files 5 Answers
Muting Audio 2 Answers