Fun little experiment I did in another thread. In order to write a new Component you have to define an accompanying ComponentGetter<>, which in this example I've prefixed with an underscore.
Strict
#REFLECTION_FILTER="*"
Import reflection
Class Entity
Field components := New StringMap<Component>
Method AddComponent:Void(component:Component)
Local key:String = GetClass(component).Name
components.Set(key, component)
component.owner = Self
End
End
Class Component
Field owner:Entity
End
Class ComponentGetter<T>
Global name:String
Function GetFrom:T(entity:Entity)
If name = "" Then name = GetClass( New T() ).Name 'be aware of this New
Return T( entity.components.Get(name) )
End
End
Class _PositionComponent Extends ComponentGetter<PositionComponent> End
Class PositionComponent Extends Component
Public
Method X:Int() Property Return _x End
Method X:Void(x:Int) Property _x = x End
Method Y:Int() Property Return _y End
Method Y:Void(y:Int) Property _y = y End
Method New(x:Int, y:Int)
Self._x = x
Self._y = y
End
Private
Field _x:Int, _y:Int
End
Function Main:Int()
Local myEntity := New Entity()
myEntity.AddComponent( New PositionComponent(16, 24) )
Local position := _PositionComponent.GetFrom(myEntity)
Print "X: " + position.X + " Y: " + position.Y
Return 0
End
|