Trouble optimizing code

I’m not to sure how to do it. I tried and then I broke my ai. My cpu when playing goes from 20% to 80-100%
and after a while, it crashes unity in editor and or build.

No one’s going to go through your whole repo telling you how to optimize it. If you have a specific question on how to improve the performance of a specific but of code, post that, and people might be able to offer an approach.

But in general, the solution to your performance problems is pretty simple: Just learn to use the Profiler: Unity - Manual: Profiler overview There’s no real secret to this. It’s how we all identify performance problems in our games.

2 Likes

In addition to what @dgoyette said, your description of the game eventually crashing could be indicative of a memory leak. I would suggest looking at the memory profiler as well as the CPU. See if some kind of object is ever increasing over time in your game’s memory.

I looked at the profiler, but I’m not too sure how it works, what I should be looking at, and what it should look like. Could you give me an example of what it should look like? Mine looks like this.

A profiler isn’t supposed to “look” any particular way.

Optimizing is all about two things:

  1. not doing what’s causing the problem

  2. doing less of what is causing the problem

First you must find what is causing the problem.

The profiler can help you do this.

It may be useful to start with a blank project and a good profiler tutorial to get a feel for things.

There are many tutorials on the profiler. Work through at least one or two.

Another route is to make changes to your game to turn off various portions until you identify (by elimination) the portions causing problems.

Alternatively if you are using source control (YOU SHOULD BE!), then revert back to before what caused the problem and move forward through your commits until the problem manifests, then you can see what changed between commits.

1 Like

Based on that screenshot of the profiler there doesn’t seem to be a performance issue at all, you’re running at 250fps. Are you just concerned with high cpu usage?

As for the crash it’s possible you have an infinite loop somewhere in your code.

I do have an infinite loop. it’s so it spawns my enemies every few minutes. Is that bad?

It’s bad if it’s infinite within a single game frame. That will cause a crash. If it’s in a Coroutine with a yield return that’s probably ok.

1 Like

It is a Coroutine with a yield return but I think the problem is I have too much of the spawners. I’m going to do some testing…

Are you starting your coroutine within Update()? Don’t do that. A new coroutine gets started every frame, while the old ones will continue to run.

(sidenote: as mentioned, no one’s going to download your project file, I recommend posting the spawning script in code tags, where we’ll all look at it and probably find the problem pretty quick.)

1 Like

it was in update, but it had a bool that was false. when it ran it was turned true. I then decided to put it in awake

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    public GameObject[] Enemies;
    private int index;
    private float WaitTime;
    private void Awake()
    {
        WaitTime = Random.Range(30, 150);
        StartCoroutine(SpawnEnemy());
    }
    IEnumerator SpawnEnemy()
    {
        if (GameObject.FindGameObjectsWithTag("Enemy").Length <= 10)
        {
            while (true)
            {
                yield return new WaitForSeconds(WaitTime);
                WaitTime = Random.Range(30, 150);
                index = Random.Range(0, Enemies.Length);
                GameObject NewEnemy = Instantiate(Enemies[index], transform.position, transform.rotation) as GameObject;
                NewEnemy.transform.position = transform.position;
            }
        }
       
       
    }
}

When you get the crash, take a look at the end of the log file (either player log for a build, or editor log if in the editor). It may indicate the cause of the crash. If it actually were a memory leak, it may say something to the effect of unable to allocate some memory for example.

As far as CPU usage, by default for a standalone build Unity will maximize framerates until it hits a hardware bottleneck. Whatever is the bottleneck in your machine, be it CPU, GPU, etc, will be at 100% utilization. If you don’t like that behavior, you can use vsync or Application.targetFrameRate to limit frame rates. But purposely leaving extra hardware performance on the table, is not something players are typically fans of. (though its important for mobile and dedicated server builds)

1 Like

I think as long as it’s not a value lower than 60 fps you’ll get few complaints. (Only exception would be some twitch reaction based game like a FPS) I suspect for most genres players would prefer “my laptop/phone isn’t setting my knees on fire” over “I’m not taking full advantage of my 144Hz display”.

1 Like

Next to the Profiler documentation and the content on the Learn section of the Unity webpage, this Unite Now Introduction video is probably a good place to get started with profiling.

If you are planning on shipping this game on anything else than the Desktop Platform you are running your Editor on, you should also remember to keep making builds and deploying them to the lowest common denominator(s) in terms of their hardware capabilities. Make debug builds and attach the profiler to those. Playmode profiling is nice for quick iteration while optimizing something problematic discovered while profiling a build, but if you are e.g. looking at WebGL, Mobile or Switch as potential platforms to release to, you might have an awkward awakening when only ever checking the performance on a powerful desktop machine until you’ve built all your game systems, got somewhere through adding all your content and suddenly realizing that you are hitting hard limits there. Making changes to base systems and having to lower your asset quality too late in production because stuff doesn’t fit anymore is painful and time consuming (and through that, costly).

Always: profile early & monitor performance regularly, on device, specifically lowest end platforms/devices. No need to optimize everything to approach speed of light if it isn’t a problem but if you have core systems (like your spawn loop) that will scale with the content you throw at it (and off course Unity’s rendering systems also scale with load) make sure you get to a vertical slice scenario fast (super prototyp-y suffices, placeholder assets and all) that mimics what your final vision is in terms of sizes, counts and general load. If that vertical slice runs fine, you’re golden. Keep building and monitor it.

That said, you might want to implement a pooling system for your spawner to avoid spikes in frame time whenever you spawn a new wave. There should be plenty of tutorials and resources on how to do that all over the web, forums and youtube.

1 Like