- Home /
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!
is the script attached to the gameobject you are disabling? if so then your script will not be called anymore once you set active to false
Ah, thanks. I solved it but that just helps make since of it all.
Answer by Lovrenc · Jul 29, 2013 at 05:42 PM
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
Thank you! I actually got it to work about a $$anonymous$$ute ago, came to check here for other ideas.... the way you are describing is much better than what I just did! :D Thanks again.