- Home /
Adding an integer
I was in the middle of working on a project when i got stuck. I'm not sure if it's because i mixed up the usage of actionscript and javascript but i cant seem to find the problem.
I did a test to increase a varible by 1 but it doesnt seem to be working. I wrote this to test in the update function.
var test : int;
test++;
print(test);
However, all I got from the print is "1". My main problem was to increase it by 1 per second so i did this.
var test = 0;
test += (1*Time.deltaTime);
print(test);
But I just get "0".
Can anyone correct me or point me in the right direction?
Answer by Ben Holmes · Feb 13, 2012 at 08:33 PM
I see two problems here.
One, you need to declare your variable outside of the function you're using it in otherwise it will always be defined as 0, then incremented;
The other problem is that you're defining this variable as an integer (by setting it to 0, which is expressed as an int), but what you're adding is a small float value which gets rounded to zero;
Time.deltaTime is a float value which is the amount of seconds between frames (so 0.01666 for 60 frames per second). when you try to add this to an int it castes it to an integer value which means it gets rounded to zero then added to your integer. So you're solution might be to store 'test' as a floating point value.
Answer by LastTemplar · Feb 13, 2012 at 07:00 PM
Well, I guess the problem is that you instantiate the variable whenever the Update function is called, so what it does is that it creates the variable, assigns zero to it, increments it and the it starts over. Try creating the variable outside the Update() function, something like this: (I'm not too good with Javascript so I'll write an example in C#)
public int test; void Update() {test++; print(test); }
Depending on your need you could also create a for loop.
Answer by Kievern · Feb 14, 2012 at 07:07 AM
Thanks! Got it to work with
var time : float;
var index = 0;
function update(){
time += (1*Time.deltaTime){
if(index <2){
if(time >= 0.43){
time = 0;
index++;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613064040im_/https://answers.unity.com/themes/thub/images/avi.jpg)