Game objects are basic non functional containers and by default only represent a position, rotation and scale.
Game objects can be placed in other game objects in a parent child relationship. Where the child gameobject inherits the position rotation and scale of its parent.
Adding components to game objects give them function. These components are added directly to gameobjects.
A single game object can have multiple components that serve many purposes.
s&box provides many default components for common features. Like rendering models and giving physics to objects.
its impossible for the engine to have components that solve every problem. But it doesnt have to, we can create our own custom components using c#.
On a game object click Add Component and choose new simple component save this component and open it in your preferred editor, I recommend Visual Studio or Rider.
To change what editor opens by default open the edit menu then preferences and change the code editor in the general tab.
Components provide many methods for us to write code. Each of these component methods will be called at different times. To keep it simple we are only going to look at a few.
The OnUpdate method will be called every frame while the OnStart method will only be called when the component is first created
To help visualize this we can log to the console using Log.Info
The onstart log is only called once while on update is being called every frame.
Lets check for user input using Input.Pressed. This is a method that returns true if the action was just pressed this frame. You can see all the default actions that you can use in the projects settings menu in the input tab.
By default “Attack1” is bound to left click. Adding another log will show that the code inside of the if statement is only called for every full press of our left click.
Components can expose settings to the editor using c# properties.
Create a c# property and give it the [Property] attribute. You can expose many types to the editor this way
Lets expose a gameobject property so we can reference a gameobject that exists in our scene
create a property with the type of gameobject and call it Target. Make sure its a C# property and has the property attribute. Then look at the inspector for your component in the scene.
You can see our target isnt pointing to anything. Create a new cube in your scene and drag the gameobject onto your property.
With a reference to the cube game object we can get any component attached to it.
Lets get its model renderer using the get component method.
then set its tint to a random color. Since our code is inside our input check everytime we press left click the tint will change to a random color.