S&box Wiki

Revision Difference

GameObjects#563001

<cat>Code.Game</cat> <title>GameObjects</title> # GameObjects GameObjects are the fundamental building blocks of a [Scene](https://docs.facepunch.com/s/sbox-dev/doc/scenes-LT2kjsMBy4). A GameObject can have [Components](https://wiki.facepunch.com/sbox/Components) which can provide a wide variety of functionality. ## Transform You can manipulate a GameObject through code, including its [Transform](https://asset.party/api/Transform/). A GameObject's Transform is held relative to its parent. ```cs // Set world position GameObject.Transform.Position = new Vector3( 100, 100, 100 ); GameObject.WorldPosition = new Vector3( 100, 100, 100 ); // Set position relative to parent GameObject.Transform.LocalPosition = new Vector3( 100, 100, 100 ); GameObject.LocalPosition = new Vector3( 100, 100, 100 ); // Set world transform GameObject.Transform.World = new Transform( Vector3.Zero, new Angles( 90, 90, 180 ), 2.0f ) ``` ## Tags GameObjects have tags, which can be used a variety of ways. Some common usages include only returning GameObjects from a trace that include or omit certain tags, or determining what objects you want a specific camera to render. ```cs GameObject.Tags.Add( "player" ); // Only trace against GameObjects that include the player tag var tr = Scene.Trace.Ray( myRay, 64f ).WithTag( "player" ).Run(); ``` You can add/remove tags in the Editor at the top of the Inspector for that GameObject. To add a new tag, click the tag+ icon and then pick an existing one or type the name of a new tag and hit Enter. <upload src="3b92d/8dc2c1e05b056c5.png" size="21865" name="image.png" /> ## Directory If you want to find a GameObject in your scene by name or Guid, you can use `Scene.Directory`. You can also query `Scene.GetAllObjects( bool enabled )`. These are expensive, so you shouldn't do it all the time (such as in OnUpdate). ```cs var go1 = Scene.Directory.FindByName( "my_go" ); var go2 = Scene.Directory.FindByGuid( "9bb977ad-5e74-4915-9ef7-c0249ec396d2" ); var go3 = Scene.GetAllObjects( true ).Where( go => go.Tags.Has( "player" ) ); ``` ## As a Property Sometimes, a Component may need a reference to a particular GameObject in your scene. You can set it as a property, and then reference it without having to iterate through all GameObjects in the scene to find it. ```cs public sealed class MyComponent : Component { [Property] public GameObject Body { get; set; } protected override void OnStart() { var bodyClone = Body.Clone(); bodyClone.Transform.Position = new Vector3( 100f, 100f, 100f ); bodyClone.WorldPosition = new Vector3( 100f, 100f, 100f ); } } ```