Search Unity

Memory Leak Problems?

Discussion in 'Getting Started' started by arnoldhide, Jun 25, 2020.

  1. arnoldhide

    arnoldhide

    Joined:
    Jun 2, 2014
    Posts:
    9
    Hi. I'm just started learning about 2 weeks now. I pretty much already grasped basic usage and c# programming in unity.
    But when I looking around the internet, there's 1 problem that usually happens in indie games which is "memory leak".
    Is memory leak possible in unity and do you guys have any pointer where I should be careful to prevent this?

    thank you in advance.
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Yes, memory leaks are possible in any software.
    In the case of Unity (or rather, C#), events can potentially cause memory leaks.

    Whenever subscribing to an event (using
    +=
    ), always be sure to unsubscribe from it at some point (using
    -=
    ), otherwise it will remain in memory even if you destroy the object containing the subscription.

    Unity has a custom UnityEvent class that works the same way and should be treated the same way.

    See these other resources for more info:
    https://forum.unity.com/threads/can...-and-resources-load-cause-memory-leak.626080/
    https://michaelscodingspot.com/5-te...ory-leaks-by-events-in-c-net-you-should-know/
     
    arnoldhide likes this.
  3. arnoldhide

    arnoldhide

    Joined:
    Jun 2, 2014
    Posts:
    9
    Thank you very much!
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    There's things you can do on the Unity side, like keep creating new materials you forget to destroy to create a memory leak. Say you instantiate a prefab, create a new material for it, then destroy the object without destroying the material. Then you do that thousands of times. You might get yourself into some trouble.

    But C# itself is on the forgiving side, seeing that it is a managed language using a garbage collector. So other than a few exceptions, memory leaks aren't something you need to worry about as much compared to some other languages. The Profiler can help you both detect them if/when they occur, and track them down.