Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Trouble optimizing code

Discussion in 'Scripting' started by Jadecraft4, Jul 22, 2020.

  1. Jadecraft4

    Jadecraft4

    Joined:
    Mar 1, 2020
    Posts:
    27
    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.
     
    Last edited: Jul 22, 2020
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,120
    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: https://docs.unity3d.com/Manual/Profiler.html There's no real secret to this. It's how we all identify performance problems in our games.
     
    MartinTilo and Joe-Censored like this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    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.
     
  4. Jadecraft4

    Jadecraft4

    Joined:
    Mar 1, 2020
    Posts:
    27
    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. Profiler.PNG Profiler2.PNG
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,769
    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.
     
    Joe-Censored likes this.
  6. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    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.
     
  7. Jadecraft4

    Jadecraft4

    Joined:
    Mar 1, 2020
    Posts:
    27
    I do have an infinite loop. it's so it spawns my enemies every few minutes. Is that bad?
     
  8. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    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.
     
    APSchmidtOfOld likes this.
  9. Jadecraft4

    Jadecraft4

    Joined:
    Mar 1, 2020
    Posts:
    27
    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...
     
  10. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    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 ]code tags[/code], where we'll all look at it and probably find the problem pretty quick.)
     
    PraetorBlue likes this.
  11. Jadecraft4

    Jadecraft4

    Joined:
    Mar 1, 2020
    Posts:
    27
    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
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemySpawner : MonoBehaviour
    6. {
    7.     public GameObject[] Enemies;
    8.     private int index;
    9.     private float WaitTime;
    10.     private void Awake()
    11.     {
    12.         WaitTime = Random.Range(30, 150);
    13.         StartCoroutine(SpawnEnemy());
    14.     }
    15.     IEnumerator SpawnEnemy()
    16.     {
    17.         if (GameObject.FindGameObjectsWithTag("Enemy").Length <= 10)
    18.         {
    19.             while (true)
    20.             {
    21.                 yield return new WaitForSeconds(WaitTime);
    22.                 WaitTime = Random.Range(30, 150);
    23.                 index = Random.Range(0, Enemies.Length);
    24.                 GameObject NewEnemy = Instantiate(Enemies[index], transform.position, transform.rotation) as GameObject;
    25.                 NewEnemy.transform.position = transform.position;
    26.             }
    27.         }
    28.        
    29.        
    30.     }
    31. }
     
  12. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    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)
     
    MartinTilo likes this.
  13. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    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".
     
    Joe-Censored likes this.
  14. MartinTilo

    MartinTilo

    Unity Technologies

    Joined:
    Aug 16, 2017
    Posts:
    2,161
    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.
     
    Kurt-Dekker likes this.