I’ve been looking up memory leaks lately, and was getting concerned the way I’m using objects might be causing it unknowningly.
In C#, if I declare a new instance of a class with say “new MyClass()”, after using the instance, do I need to manually delete that instance, or does C# do it on its own? I remember in C++ you had to do it manually with Delete(), but never noticed in C#.
C# is a managed language, where memory is handled by the garbage collector. When there are no more references to an object, it will automatically be freed when the garbage collector runs the next time.
You can still create memory leaks by holding onto references to objects you no longer need. A common example is registering an event listener but then never removing it. The delegate added to the event contains a reference to the object its method belongs to, so the garbage collector will see a reference in the event list and not free the object.
Unity also uses non-managed C++ objects in the background, which you use through C# wrappers. This includes e.g. game objects or scripts but generally everything deriving from UnityEngine.Object. Unity has its own garbage collection to try to free unused native objects but it’s good practice to explicitly call Destroy on Unity objects when you no longer need them.