- Home /
What's wrong with the % operator? Simple question.
I'm trying to get my code to execute at certain frequencies.
So it's rather simple:
time++;
if(time%40==0) cycle2++;
In my other game engine, this executes my code every 40 frames, but It's kind of random in Unity. What do I have to do in Unity to make this work?
This will not work if time is a float. If so, declare it as int, or compare to a small value ins$$anonymous$$d of 0:
if (time%40 < 0.001) cycle2++;
Comparing floats is tricky: both must be exactly the same to produce an equality, and this rarely occurs.
Answer by haroonalam · Jan 19, 2012 at 08:18 AM
check the Time properties in unity docx. This is what I had done to trigger function on specific time:
float m_time = 0.0f;
void Update()
{
m_time += 0.01f;
if (m_time >= CertainFrequency)
{ //do something..
m_time = 0.0f; }
}
Hmm.. that's unfortunate I can't just use an operator. Oh well, I suppose it wouldn't hurt to add some more ti$$anonymous$$g variables. :/
it seems strange, I am using % its perfectly working, make sure you are importing libraries
Answer by Kryptos · Jan 19, 2012 at 08:50 AM
Update is called whenever possible. This means that it is not called at a fixed rate.
If you want to call something every n frames, you can use Time.frameCount:
int n = 40;
void Update()
{
if( (Time.frameCount % n) == 0 )
{
// do something
}
}
But you can also use a floating value to call something every n seconds:
int fSeconds = 5.1f;
int fElapsedTime = 0.0f;
void Update()
{
if( Mathf.Repeat( fElapsedTime, fSeconds ) == 0 )
{
fElapsedTime += Time.deltaTime;
// do something
}
}
This is what I'm looking at in particular if this makes any sense.. //Spot positions if((timeAll+(0*sFrequency))%(4*sFrequency)==0) {vLine1=v$$anonymous$$irror;cycle1++;} if((timeAll+(1*sFrequency))%(4*sFrequency)==0) {vLine2=v$$anonymous$$irror;cycle1++;} if((timeAll+(2*sFrequency))%(4*sFrequency)==0) {vLine3=v$$anonymous$$irror;cycle1++;} if((timeAll+(3*sFrequency))%(4*sFrequency)==0) {vLine4=v$$anonymous$$irror;cycle1++;}
Answer by Rush3fan · Jan 19, 2012 at 09:24 AM
Sorry that didn't format well..
//Spot positions
if((timeAll+(0*sFrequency))%(4*sFrequency)==0)
{vLine1=vMirror;cycle1++;}
if((timeAll+(1*sFrequency))%(4*sFrequency)==0)
{vLine2=vMirror;cycle1++;}
if((timeAll+(2*sFrequency))%(4*sFrequency)==0)
{vLine3=vMirror;cycle1++;}
if((timeAll+(3*sFrequency))%(4*sFrequency)==0)
{vLine4=vMirror;cycle1++;}
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Script Efficiency 1 Answer
Array Problem - Error Code BCE0022 2 Answers
Official Unity Space Shooter Tutorial 1 Answer
My AI keeps flickering between stopping and moving. 1 Answer