Rust Wiki

Revision Difference

Entities#526547

<cat>Dev</cat>⤶ <title>Entities</title>⤶ ⤶ ⤶ ⤶ # How To Spawn⤶ ⤶ ⤶ ## Prefab Name⤶ ⤶ The prefab name represents the full path of the prefab inside the game files. ⤶ ⤶ It always starts with `assets/` and will be completely lowercase.⤶ ⤶ ## Position⤶ ⤶ The position in the world where the entity will be placed. ⤶ ⤶ The default position is 0,0,0 which is the center of the map at water level.⤶ ⤶ ## Rotation⤶ ⤶ The rotation of the entity after being spawned. ⤶ ⤶ `There will be a section on Quaternions later, but simplified explaination here for now:`⤶ ⤶ There are there axis:⤶ ⤶ * The X axis goes from your left to right.⤶ * The Y axis goes from above to below you. ⤶ * The Z axis goes from front to back.⤶ ⤶ Your rotation can be represented by your rotation by turning each axis, which leads to the following behaviour:⤶ ⤶ * X rotation = leaning forward and backwards⤶ * Y rotation = turning left and right⤶ * Z rotation = tilting left and right⤶ ⤶ This means you represent your rotation as 3 numbers: `( 'x' rotation, 'y' rotation, 'z' rotation )`. These are called `Euler` (aka `Human readable`) angles. However there is one catch:⤶ ⤶ Internally a Quaternion represents your rotation as 4 numbers which makes the math easier for a computer but near impossible to understand as a human.⤶ ⤶ To solve this problem we have helper functions. You can use `Quaternion.Euler(x,y,z)` to create a new rotation based on the `Euler` angles. ⤶ ⤶ If you want to convert an existing rotation back to the `Euler` angles just use `.eulerAngles` on a rotation.⤶ ⤶ ```csharp⤶ ⤶ //Create a new rotation that is 45° to the left⤶ ⤶ Quaternion rotation = Quaternion.Euler(0,45,0);⤶ ⤶ ⤶ ⤶ //Turn the rotation back to human readable⤶ ⤶ Console.WriteLine( rotation.eulerAngles );⤶ ⤶ > Prints (0, 45, 0)⤶ ⤶ ```⤶ ⤶ ⤶ The code to spawn an entity will make a lot more sense now that we know what all the parameters mean.⤶ ⤶ #Spawn Entity Code⤶ ⤶ The first part of spawning something is to create the entity. The function takes the 3 parameters described above into this function: ⤶ ⤶ ```csharp⤶ ⤶ GameManager.server.CreateEntity(string prefabName, Vector3 position, Quaternion rotation)⤶ ⤶ ```⤶ ⤶ We store the result in a variable of type BaseEntity. ⤶ ⤶ If there was an error spawning the entity or an invalid prefab name was supplied the entity will be `null`. We should check for this before calling the `Spawn()` function or we risk throwing an error.⤶ ⤶ A full example follows.⤶ ⤶ ⤶ ```⤶ ⤶ BaseEntity rowBoat = GameManager.server.CreateEntity( "assets/content/vehicles/boats/rowboat/rowboat.prefab", new Vector3( 450, 0, 1000), Quaternion.Identity( 0, 90, 0) );⤶ ⤶ if (rowBoat == null)⤶ {⤶ return;⤶ }⤶ ⤶ //Don't forget to call spawn after⤶ ⤶ rowBoat.Spawn();⤶ ⤶ ⤶ ```⤶