sbox-reactivity

A reactivity system for s&box. It makes writing code that runs in response to state changes easy. Check out https://github.com/impulsh/sbox-reactivity for documentation.

public class MyComponent : ReactiveComponent
{
	[Property, Reactive]
	public float Speed { get; set; } = 50f;

	[Reactive, Derived(nameof(_tintColor))]
	public Color TintColor { get; } = Color.Blue;

	private Color _tintColor()
	{
		// Calculate the tint color only when the speed changes
		return Math.Abs(Speed) <= 100f ? Color.Blue : Color.Red;
	}

	protected override void OnActivate()
	{
		Effect(() =>
		{
			// Create a game object when this component is enabled
			var go = new GameObject();
			var model = go.AddComponent<ModelRenderer>();
			model.Model = Model.Cube;

			// Tint the model whenever it changes
			Effect(() => model.Tint = TintColor);
			
			// Spin the object every frame while the component is enabled
			Frame(() =>
			{
				var angles = go.LocalRotation.Angles();
				angles.yaw += Speed * Time.Delta;

				go.LocalRotation = angles;
			});

			// Destroy the object when the component is disabled
			return () => go.Destroy();
		});
	}
}