Can't set object to true (C#!)

Hi. I am trying to make a “blink” effect on my custom first person controller character, and I have it almost working. I have a countdown timer and you are automatically blinking when the game starts… it waits 3 seconds and unblinks. Now, I am trying to prototype continuos-blinking, with the click of the mouse button (it will all eventually be random, I know how to do that). But, I am having some issues with my script. Here it is:

`using UnityEngine;
using System.Collections;

public class Blink : MonoBehaviour {

public float timeLeft = 10.0f;

void Update () {
	
	timeLeft -= Time.deltaTime;
	
	if (timeLeft < 1.0f) {
		
		gameObject.active = false;
	
	}

	if (Input.GetButtonDown ("Fire1")) {

		gameObject.active = true;
	
	}
}

}`

The first part works perfectly fine. I start the game with the eyes closed, and 3 seconds later they open up (the cubes around the player are un-activated). But the second part simply does not work. No errors, just does not work.

(ALSO: I have tried putting the second block of code I am having trouble with (the second if statement) in another section like Awake, and still get the same results.)

I have tried different ways of writing it, such as gameObject.active = true/false;, GameObject.SetActive… etc. etc.

Please, any help would be greatly appreciated.

Thanks!

This has nothing to do with c#

gameObject.active = false;

Here you set your object into inactive state. Objects scripts are NOT CALLEED ANYMORE. Therefore

if (Input.GetButtonDown ("Fire1")) {

   gameObject.active = true;

}

can never be executed. Script is NOT CALLED IN THE LOOP ANYMORE.

What you could do is

  • use a simple variable for your active/inactive state and execute code according to it
  • activate this object from script that is beeing called (like gameState script or w/e)

For instance:

float timeBetweenBlinks = 10f;
float timeSinceLastBlink = 0f;

void Update() {
  timeSinceLastBlink += Time.deltaTime;
  if(timeSinceLastBlink > timeBetweenBlinks) {
    Blink();
    timeSinceLastBlink = 0f;

  }
}

Or even better, lern and use Coroutines