Creating and destroying objects
Scene objects lifetime is controlled by the Flax but the game can also access New/Destroy methods that allow to manage the scene at runtime. Some games keep a constant number of objects in the scene, but it is very common for characters, treasures and other object to be created and removed during gameplay.
Spawning objects
C#
Example code that spawns a new point light:
public override void OnStart()
{
var light = new PointLight();
light.Color = Color.Blue;
light.Parent = Actor;
// object will be part of the scene hierarhcy
// engine will destroy it on scene unload
}
You can add new scripts to any objects by using AddScript method:
Note
Scene objects (actors, scripts) should not use constructors other than initialize itself (defaults).
Removing objects
Flax supports immediate and delayed objects removing system. This helps with cleanup up the scene from killed players or unused actors.
using FlaxEngine;
public class MyScript : Script
{
public SpotLight Flashlight;
public override void OnStart()
{
Destroy(ref Flashlight);
}
}
Here is an example script that will remove object after a specified timeout (in seconds):
using FlaxEngine;
public class AutoRemoveObj : Script
{
[Tooltip("The time left to destroy object (in seconds).")]
public float Timeout = 5.0f;
public override void OnStart()
{
Destroy(Actor, Timeout);
}
}
In the same way you can remove scripts:
Language-specific
C#
Various components and APIs that are specific to C# language use Dispose()
pattern and implement IDisposable
interface for convenience. For example:
Control
- GUI controls useDispose
method to destroy UI element,InputAxis
/InputEvent
- virtual input reading utility has to be released viaDispose
,
C++
- Use utility macros:
SAFE_DISPOSE
,SAFE_RELEASE
,SAFE_DELETE
to cleanup objects, depending on the method to call. - Graphics objects such as
GPUTexture
orGPUBuffer
can be cleared viaSAFE_DELETE_GPU_RESOURCE
macro. Those are normal scripting objects but invokingReleaseGPU
beforehand helps to reduce memory pressure when unused. Task
system uses automatic auto-destruction of past tasks. There is no need to manually destroy objects after use.