for loop not working
Hello, I don't know why my loop isn't working :( I think it should run ten times:
var timer: float = 0.5; // set duration time in seconds in the Inspector
function Update()
{ for (var i = 1; i < 10; Debug.Log("Wolfi") ){
i = i + 1;
timer -= Time.deltaTime; // I need timer which from a particular time goes to zero
if (timer > 0)
{}
else // timer is <= 0
{
if (gameObject.active)
{gameObject.SetActive(false);}
else {gameObject.SetActive(true);}
}
}}
What are you trying to do exactly ?
Your loop will be executed **each frame**and won't wait 0.5 seconds before enabling / disabling your object.
I want to turn the lights on a police car on and off, and for now I would like one light to stay on for 0.5 secs, then turn off and that in and endless loop.
Addition: my final aim is for an endless loop, a 10 times loop would be ok for the start :)
Answer by Jessespike · Jul 06, 2016 at 08:13 PM
Remove the for-loop from Update. Do you really want a for-loop loop running 10 times every frame?
Add a reference of a GameObject to enable/disable, because disabling the GameObject will also stop the script from Updating,
Try something like this instead. Make the siren/light a child GameObject and place this script on the parent.
- ParentGameObject (place script here)
ChildGameObject (light)
.
var timer: float = 0.5; // set duration time in seconds in the Inspector
public var targetObject : GameObject; // a child GameObject
private var elapsedTime : float = 0.0f;
function Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime > timer) {
targetObject.SetActive(!targetObject.active);
elapsedTime = elapsedTime % timer;
}
}
Your answer

Follow this Question
Related Questions
For loop not looping, Conditional break and return question? 0 Answers
How to make a For Loop that waits until another action is performed before continuing? 1 Answer
Moving an instantiated gameobject problem 1 Answer
for loop crashes unity 1 Answer
Alternate the direction that a grid updates, and/or change the conditions to a For Loop mid-loop. 0 Answers