Help with My flash Light script. Having problem with Yield

Okey here it is

var Flash : Light;
var teksti : GUIText;
function Update () {
if(Input.GetKeyUp("f"))
{
if (Flash.enabled == true){
Flash.enabled = false;
teksti.text = "Flash OFF";
yield WaitForSeconds (1);
teksti.text = "";}
else{
Flash.enabled = true;
teksti.text = "Flash ON";
yield WaitForSeconds (1);
teksti.text = "";}
}
}

Problem is yield stuff, it dosent work and i cant find solution why? And is there way to make text “Fade” off? or on :slight_smile:

anyone ?

It gives error
“Script error: Update() can not be a coroutine.”

Im new at javascript and this is very annoying because i need to use it inside update() but unity dont want that?

You can’t put a yield statement inside the update function. That’s why you’re getting the error. Update cycles every frame by definition. By putting a yield statement in there, you’re asking it to pause. It creates a conflict and thus the error. You can create a separate function for your flashlight on/off routine and call the function from within update.

Also, you can make the script more efficient by using a boolean for your on/off cycle.

var lightState : boolean = true;

function Update()
{
if (Input.GetButtonUp ("f"))
{
lightState = !lightState;

FlashOnOff ();
}
}

I’m using function FlashOnOff() as an example for the function you’ll have to write. Put your other code in this function.

Also, for fading the brightness use Mathf.Lerp on the intensity component of the light.

Many thanks, all working now :slight_smile:

Just realized it’s the text you want to fade, not the light, but same principle. Use Mathf.Lerp on the material renderer.

Purri, can you share your final solution with us?

I had a bit more time this evening, so I wrote out the on/off code to clarify:

var flashlight : Light;
var yourText: String;
private var turnItOn : boolean = false;
 

function Update () 
{
if (Input.GetKeyUp("f"))
{
LightOn();
}
}

function LightOn()
{
turnItOn = !turnItOn;

flashlight.enabled = turnItOn;

if (turnItOn)
{
yourText = "Flashlight On";
}
else
{
yourText = "Flashlight Off";
}
}

Haven’t tested it, but this is how I would start. Others may have better ideas. I’m not all that advanced either. Would love to see your final code as well.

Kaya sure, here is my code: