You can either modify the composition at run time (add/remove renderer from the composition graph) or set the Enabled
property to true
or false
. Not sure if there is any benefit to either option.
If you look my first example of the SpriteCursor
script you will see how it adds a DelegateSceneRenderer
to the composition. (You could just as easily create another renderer like the SpriteCursorRenderer
and add that to the composition if you want to keep the render code separate.). If you keep a reference to the renderer you can then either remove/add it or update the enabled state as you desire.
If you add the custom renderer by modifying the composition asset then you can get it at run time and do the same (remove/add or update the enabled state). Now to get the asset defined renderer you have to know where it is in the graph and traverse the various properties casting objects to the correct type as you go. If you have a look at the SpriteCursor
script example you will get a rough idea by looking at the GetSceneRenderers
method. I generally work it out by debugging and seeing what I need to cast to etc. to get the renderer I am interested in.
But there is also another option Services
. You could make the renderer register itself as a service at start up.
[Display("Sprite Cursor Renderer")]
public class SpriteCursorRenderer : SceneRendererBase
{
protected override void InitializeCore()
{
base.InitializeCore();
//Same setup as before......
//Add this renderer as a service.
//You could also add it as a specific interface if you didn't want to expose all of a renderer
this.Services.AddService(this);
}
public override bool Enabled
{
get => base.Enabled;
set
{
base.Enabled = value;
//Do some action on enabled changing
//Game etc. might not exist when assets being compiled.
if(this.Services?.GetService<IGame>() is IGame game)
{
//Enable normal mouse cursor if this renderer is disabled.
game.IsMouseVisible = !value;
}
}
}
protected override void Destroy()
{
//Unregister this as a service if renderer removed from composition.
this.Services.RemoveService<SpriteCursorRenderer>();
base.Destroy();
//Clean up stuff here.
}
}
Then in your scripts get the service and change Enabled state:
public override void Update()
{
//...
if (Input.IsKeyPressed(Keys.M) &&
Services.GetService<SpriteCursorRenderer>() is SpriteCursorRenderer scr)
{
scr.Enabled = !scr.Enabled;
}
}
I believe there is also the option of not using the composition graph at all. I think you can create a GameSystem
and add that to the Game.GameSystems
Collection. And do the drawing in there. You would just have to make sure the draw order was after the built in rendering system. I have not attempted this myself though.
Hope that helps.