If I use a while loop similar to the example below:
void main() {
// 1. declare and initialise variables
int counter = 1;
// 2. now do the while loop
while(counter < 5 )
{
printLine("counter is equal to " + counter);
// 3. add 1 to the value of counter
counter = counter + 1 ;
}
// 4. the while loop has finished,
//so program continues on to here
printLine("Goodbye");
}
If I define the counter inside the loop, and it gets called before it finishes will it run two loops with their own counters or will it break both counters? I will have a loop that runs for about 2-3 seconds but the trigger can happen in less time, which is fine it will just instantiate two objects but I am just wondering if I can do a loop like that and still have it work properly, it’s it’s being run concurrently.
EDIT – Adding some more info so it makes a bit more sense.
What I want to do is have a game object instantiate, move up at a speed of 1/x^2 and fade out opacity until it gets to a certain point then destroys itself. It’ll actually be a score counter on my GUI (I’m using 3DText on a plane so I can move it). Thing is the actual movement will go for about 2 seconds but I can kill an enemy faster than that so I want to be able to instantiate other object and run that same while loop. Or if the loop is attached to the prefab I’m spawning will that not have any conflicts with the original?
This is a very bad way to wait for a certain time because you can never be certain, that it will always take the precise same amount of time on your machine and it may be totally different on another one.
If you want to wait for a certain time, you should always use the actual system time and wait for the actual amount of time to pass.
senad is right, you better use yield or System time to do a time based operation
an example by using system time is
var startTime : float;
var duration : float = 3.0; // set waiting time to 3 seconds
//called before the first frame update
function Start(){
startTime = Time.time;
}
//called every frame update
function Update(){
if(Time.time - startTime >= duration){
//Instantiate your object there
...
//wait the next duration to instantiate new object
startTime = Time.time
}
}
So its like giving a pop-up score that will be showed for a duration time, like 3 seconds, each time the player kill an enemy?
if that’s the case, i think attaching a “self destroying script” each time we instantiate score object is a good alternative.
In your main script:
var score:GameObject;
function Update(){
if(popScore()){
Instantiate(score);
}
}
function popScore(): boolean {
//check whether we need to pop up score
}
score is a GameObject whith a self-destructing script attached. The script look like this:
var destructionTime : float;
function Start(){
Destroy(this, destructionTime);
}
of course, in the self-destructing script you can add other code to make the score fade away & other logic so the score disappear smoothly