I’m trying to create a lightning flash effect where a UI overlay covering the screen fades in and out on repeat (the repeat is just for testing), and here’s what I have:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class lightning : MonoBehaviour
Image Lightning;
float flash;
void Start ()
{
Lightning = GetComponent<Image>();
Strike(1, 1);
}
void Strike (float Intensity, float Duration)
{
// Flash fade-in
for (flash = 0; flash < Intensity; flash = flash + Time.deltaTime / Duration)
{
Lightning.color = new Color(0.8f, 0.8f, 0.8f, flash); // Update overlay alpha
}
// Flash fade out
for (flash = Intensity; flash > 0; flash = flash - Time.deltaTime / Duration)
{
Lightning.color = new Color(0.8f, 0.8f, 0.8f, flash); // Update overlay alpha
}
// Ensures flash ends up on 0
flash = 0;
// Restarts lightning strike
Strike(1, 1);
}
The issue from what I can tell is that only the very first increment in the for loop occurs, and then the code just stops. If I only write:
void Strike (float Intensity, float Duration)
{
flash = Intensity;
}
-Then it sets it accordingly.
I’ve only been using Unity for a few days so far, so maybe I don’t fully understand how updating works. I don’t need to use the Update() function here, do I? For note, I was using a While loop before but switched over to a For loop for the sake of cleanliness, but they yielded the exact same result.
a couple of things:
– gjfStart()is called exactly once, which probably isn't what you need for fading over time...consider putting it inUpdate()you're callingStrike()recursively... that's why the code appears to stop. there a many examples of how to fade colors... one of the easiest ways is to use one of the many tween libraries which can produce the desired effects. take a look at [doTween][1] [1]: http://dotween.demigiant.com/download.phpYou should seriously consider writing a shader for this. Since it is a flat color, and you are just adjusting alpha; you can do this in a very fast shader, and you'll have more control in the end. I am unsure how to connect a shader to the camera though.
– rageingnonsenseGlad I could help. Animations can be really powerful once you figure everything out.
– Fanttum