S&box Wiki

Components

Components

Components are bits of functionality you can add to GameObjects. You can create a component to do anything you wish. There are also numerous components that exist in the s&box engine by default. You can find a list of example components within the sbox-scenestaging repo on Facepunch's GitHub.

Properties

An attribute [Property] can be added to a property member on your component class, which allows you to slot in information about the property outside of code. This allows your component to be more re-usable.

public sealed class Health : Component { // MaxHealth can be changed within the editor now, but defaults to 100f. [Property] public float MaxHealth { get; set; } = 100f; public float CurrentHealth { get; set; } protected override void OnStart() { // Set current health to max health when this component starts up CurrentHealth = MaxHealth; } }

See the Attributes and Component Properties page for more info and examples.

Methods

There are a number of methods you can override when making your own component. You can find a full list here. Below is an example of overriding a method.

public sealed class MyComponent : Component { // OnUpdate is called every frame protected override void OnUpdate() { Transform.LocalRotation = Rotation.Random; } }

Enabling and Disabling

You can enable or disable a component through code. When a component is disabled, methods like OnUpdate, OnFixedUpdate, and more are skipped. Whenever you enable a component, OnStart and OnEnabled will be called (in that order). Disabling a component calls OnDisabled.

var comp = Components.Get<Health>(); if ( comp.CurrentHealth <= 0 ) { // Will trigger OnDisabled on Health comp.Enabled = false; }

Managing a Component on a GameObject

Most often, you will want to add components to a GameObject outside of the codebase (through the scene editor). But sometimes, there are cases you want to add to or remove from a GameObject directly.

// Gets Health, or creates it if it does not exist. var comp = Components.GetOrCreate<Health>();

From within a component, many properties of a GameObject (such as Transform, Components, Scene, etc) are exposed for you for convenience.

public sealed class MyComponent : Component { protected override void OnStart() { // Changing the Transform on a Component simply adjusts the Transform of the GameObject. Transform.Position = new Vector3( 10f, 0f, 10f ); if ( Components.TryGet( out Health health, FindMode.EnabledInSelfAndChildren ) ) health.Destroy(); } }