-
Notifications
You must be signed in to change notification settings - Fork 31
EgoComponents and Component Queries
At the start of the game, EgoCS makes sure that every GameObject has an attached EgoComponent
.
A GameObject's EgoComponent
uses a bitmask to keep track of attached components, and saves you from writing multiple GetComponent<C>()
checks. This also makes querying attached Components super fast.
You can query if the GameObject has one or more Components attached using HasComponents<...>()
, where the type parameters are Component types:
var egoComponent = gameObject.GetComponent<EgoComponent>();
// One Component
if( egoComponent.HasComponents<Rigidbody>() )
{
// ...
}
// Multiple Components
if( egoComponent.HasComponents<Rigidbody, BoxCollider, ExampleComponent>() )
{
// ...
}
When you pass multiple Component types into HasComponents<...>()
, it will only return true
if all of the specified Component types are attached to the GameObject.
You can check if a GameObject has certain Components and get references to them if it does, all in one shot using TryGetComponents<...>()
:
var egoComponent = gameObject.GetComponent<EgoComponent>();
Rigidbody rigidbody;
BoxCollider boxCollider;
Example example;
// One Component
if( egoComponent.TryGetComponents( out rigidbody ) )
{
rigidbody.AddForce( Vector3.up );
}
// Multiple Components
if( egoComponent.TryGetComponents( out rigidbody, out boxCollider, out example ) )
{
rigidbody.AddForce( Vector3.down );
// ...
}
You don't need to specify the type parameters for TryGetComponents<...>()
since the compiler can infer them from the function parameters.
Like with HasComponents<...>()
, TryGetComponents<...>()
will only return true
, and send out
Component references if all of the specified Component types are attached to the GameObject.
For now, HasComponents<...>()
and TryGetComponents<...>()
only support querying up to 5 Component types at once. This limit will be increased soon.
These methods are especially useful for collision detection, as they let you quickly and easily filter out undesired GameObjects:
// Let's say we're making a Breakout clone:
public class BallCollisionSystem : EgoSystem
{
public override void Start()
{
EgoEvents<CollisionEnterEvent>.AddHandler( Handle );
}
// Here, we're detecting when the Ball hits a Brick
void Handle( CollisionEnterEvent e )
{
if( e.egoComponent1.HasComponents<Brick>() && e.egoComponent2.HasComponents<Ball>() )
{
// The first colliding GameObject is a brick
DestroyBrick( e.egoComponent1 );
}
else if( e.egoComponent1.HasComponents<Ball>() && e.egoComponent2.HasComponents<Brick>() )
{
// The second colliding GameObject is a brick
DestroyBrick( e.egoComponent2 );
}
}
void DestroyBrick( EgoComponent brickEgoComponent )
{
// ...
}
}