The702Guy
The702Guy

Reputation: 31

Slow down time effect causing FPS issues in Unity

so I'm using a slow down time effect I saw in a tutorial to randomly slow down time when an enemy dies. It works fantastically unless it happens when there are a lot of enemies spawned in at once. I have narrowed it down to this definitely being the issue as if I deactivate it I get no FPS issues at all when killing enemies even with large amounts of enemies. Now I don't know why this is happening, I believe due to all of my AI trying to do pathfinding and when the time is slowed it severely drops the FPS. The slowdown effect doesn't cause issues unless there are a lot of enemies pathfinding at once (somewhere in the 30+ range) if only a few are out it works as intended. Below is code my for the slow down time effect, is there something I can change to avoid this from happening? I am also using the A* Pathfinding Project for my AI. The SlowDownTime method is called whenever an enemy dies.

public float slowdownFactor = 0.05f;
public float slowdownLength = 2f;

void Update()
{

    if (!gameManager.GetComponent<UserInterfaceHandler>().gamePaused)
    {
        Time.timeScale += (1f / slowdownLength) * Time.unscaledDeltaTime;
        Time.timeScale = Mathf.Clamp(Time.timeScale, 0f, 1f);
    }

}

public void SlowDownTime()
{
    int randomChance = Mathf.RoundToInt(Random.Range(1.0f, 5.0f));

    if (randomChance == 4f)
    {
        Time.timeScale = slowdownFactor;
        Time.fixedDeltaTime = Time.timeScale * .02f;
    }
}

Upvotes: 0

Views: 630

Answers (1)

derHugo
derHugo

Reputation: 90724

I suspect that

Time.fixedDeltaTime = Time.timeScale * .02f;
 

is an issue.

The entire path finding stuff is based on physics and you basically force it to run the physics engine in really tiny intervals.

A lower timestep value means more frequent physics updates and more precise simulations, which leads to higher CPU load.

Have in mind that 0.0166666... (real-time) seconds (= 1/60) is the maximum frame duration if you want to achieve around 60 FPS.

You are forcing the physics engine here to calculate every 0.01 (= 0.05 * 0.2) (real-time) seconds so in case a physics / path finding update takes more then only 0.006666... seconds (6.66ms) - which is a value easily reached with many path finding runs - you will already have frame-rate drops.

I think in your case you simply want to stick to the Time.fixedDeltaTime you have and not touch it at all.


Also btw

if (randomChance == 4f) 

is quite risky and can behave unexpected (see Is floating point math broken?). In general using == on float in almost all cases will behave unexpected.

Rather use the int overload instead of floats in the first place

var randomChance = Random.Range(1, 5); 

will return int from 1 to 4 as the upper bound 5 is exclusive

and then also

if(randomChance == 4)

in order to use int == int instead of float (implicitly casted) == float

Upvotes: 1

Related Questions