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;
}
You can add new scripts to any objects by using AddScript method:
Note
Scene objects (actors, scripts) should not use constructors to prevent issues.
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: