AGK for Pascal uses semi-automatic memory management. Every AGK object can have an owner (except for the root Application object). The owner takes reponsibility of destroying the objects it owns.
This means that as long as you provide owners for your objects, that you never have to free those objects yourself. This reduces the risk of memory leaks and memory related bugs.
In a typical scenerio, you have a global TAgkApplication object. This object owns other objects that you need throughout the entire life time of the application. For example, you could have a TAgkNetwork connection that is owned by the application. Then all scenes in your application could use this connection. The application object gets destroyed automatically when you shut down the program. This will also destroy all objects owned by the application, including its scenes and the network connection in this example.
In your application, you will be running one or more scenes (see TAgkScene). You switch scenes by calling TAgkApplication.SetScene. When you switch scenes, the previous active scene automatically gets destroyed (unless you set TAgkScene.AutoFree to False to keep the scene around).
Most of your game objects, like images, sprites, sounds etc. will be owned by the scene. So switching scenes will also automatically destroy all the resources owned by the previous scene. If you want to use the same resource (like a sprite or sound effect) in multiple scenes, then you should set the owner of those resources to the application instead of the scene. Resources owned by the application stay available for the entire life time of the application.
You set the owner of an AGK object by passing it as the first parameter to the constructor. For example, you typically load images in the Startup method of your scene like this:
In this example, Self is passed as the first parameter, so the image is owned by the scene, and destroyed when the scene is destroyed.
Of course, you can always destroy an object earlier yourself if you don't need it anymore. In fact, that is recommended to free up memory or other resources, which is especially important for mobile devices. However, if you need the object throughout the life time of the scene, then there is no need to free it yourself. If will be handled automatically.
You can also take advantage of this semi-automatic memory management for your own classes. Just derive them from TAgkObject so they can be owned by other objects. Note that if you create custom constructors for those classes, that you need an Owner parameter, so that you can pass down that parameter to the inherited constructor of TAgkObject.
Copyright (c) 2012. All rights reserved.