This journal entry is a riff of that theme.
For those who don't know, Unity 3d is based heavily on the Entity-Component model. The root "entity" in Unity is the "GameObject", which along with a whole load of other things, is a container for components. Unity has a load of components ready-made out of the box, which shows how powerful this model can be. Complex GameObjects are composed from these myriad of simple objects!
So taking Boreal's article and Unity's model, it got me thinking - "how would you implement a similar system in your .NET own projects?". I'm using C#/.NET, which gives us a whole load of lovely type inference, but you can do something similar in C++ with some hacks/tweaks/black magic. I won't discuss that here, as I expect Boreal Games will cover this.
First of all, let's start with the basic definition if a component. In .NET I've defined it as very simple interface:
public interface IComponent{ string Name { get; }}
It's probably about as simple as you can get. It simply exposes its name, which is a friendly name for the component.
From here, I took a look at Unity's API documentation for the GameObject class. The following major component methods were obvious:
- AddComponent - a factory method, creates a new component instance and adds to the object
- GetComponent - a generic method which returns the added component of type TComponent, or null if it doesn't exist
- GetComponents - returns all components associated with the object
On top of this were a bunch of child methods, which pulled back all components attached to the children of this GameObject and a bunch of default strongly typed helper component properties, likely used for optimisation of commonly accessed components. For the sake of simplicity, I'm going to skip of these and focus on the core functionality.
To do this, I specified a IComponentCollection interface.
public interface IComponentCollection{ TComponent GetComponent() where TComponent : class, IComponent; IEnumerable GetComponents(); TComponent AddComponent() where TComponent : class , IComponent, new(); void RemoveComponent() where TComponent : class , IComponent;}
This is relatively simple; it allows the Add, Remove and Retrieval of components which conform to the IComponent interface we specified earlier. There's a bit of .NET generic foo which says the component type must be a class and have a default constructor, but other than that, it's simple.
So we have our component interface and our collection interface, let's implement them. For simplicity's sake, I chose to base my IGameObject interface on IComponentCollection. IGameObject has a bunch of other stuff in it, such as the InstanceId Guid and some other things you might want to add. You could choose to implement IComponentCollection in your own class if you needed, but for this example it wasn't needed.
public interface IGameObject : IComponentCollection{ bool IsActive { get; } Guid InstanceId { get; } void SetActive(bool status);}
In this demo, I chose to pick a couple of obvious properties from Unity to demonstrate that the GameObject is more than just a component collection. You could very easily add some of the nice "helper" properties you saw on the Unity GameObject, which actually return existing component instances (via GetComponent).
Great. All the key interfaces are created, let's create an implementation of GameObject.
public class GameObject : IGameObject{ Dictionary components; public GameObject() : this(Guid.NewGuid()) { } public GameObject(Guid instanceId) { this.InstanceId = instanceId; this.components = new Dictionary(); this.IsActive = true; } public bool IsActive { get; private set; } public Guid InstanceId { get; private set; } public TComponent GetComponent() where TComponent : class , IComponent { IComponent res = null; var t = components.TryGetValue(typeof(TComponent).Name, out res); if (t == false) return null; return res as TComponent; } public IEnumerable GetComponents() { return this.components.Values; } public TComponent AddComponent() where TComponent : class, IComponent, new() { var existing = this.GetComponent(); if (existing != null) throw new ComponentExistsException(typeof(TComponent).Name); // Factory method var newComponent = new TComponent(); this.components.Add(newComponent.GetType().Name, newComponent); return newComponent; }? public void SetActive(bool status) { this.IsActive = status; }? public void RemoveComponent() where TComponent : class, IComponent { var found = this.GetComponent(); if (found == null) throw new ComponentNotFoundException(typeof(TComponent).Name); components.Remove(typeof(TComponent).Name); }}
This class is really simple. It keeps an internal Dictionary of component type name and the instance.
- GetComponent simply looks up the type name requested on the generic method and returns it if it exists; failing that, it returns null.
- GetComponents simply returns the values in the dictionary.
- AddComponent checks to see if the component is already there, if so throws a custom exception. If it's not there, we create a new instance from the IComponent implementation's default constructor and add to the dictionary.
- RemoveComponent allows us to remove an existing component if it exists; if not, we throw a custom exception.
We can easily extend Add/Remove to accept of a pre-built component instance. It's up to you to add this ;)
So with this in place, let's create a custom component. Picking the simplest possible thing we can that many (if not all) GameObjects will have is the "Transform" component. In Unity, this is relatively complete - in our example I've simply created it to have a Position of Vector3d type. Realistically, your type will be more like Unity's and have a Rotation, various orientation vectors and matrices which help with using this in a 3d world.
Our TransformComponent looks something like this:
public class TransformComponent : IComponent { public string Name { get { return "Transform"; } } public Vector3d Position { get; set; } }
Very, very simple. As you see, it implements the IComponent interface, and adds it own properties to that. We could add properties, methods, events, whatever we need.
As another example, I added a simple test component for the sake of unit testing,
public class TestFakeComponent : IComponent { public string Name { get { return "this is a test"; } } public string SayHello() { return this.SayHello("Component System"); } public string SayHello(string who) { return string.Format("Hello {0}", who); } }
As long as we inherit from IComponent we're all good.
Let's see this in action. Here's some code adapted from my unit tests to show usage....
[code=:0]var go = new GameObject();var transform = go.AddComponent();transform.Position = new Vector3d(1000, 2000, 3000);
We create a new GameObject, add a new transform component to it, then modify the Position on it.
After this, we can find the transform and do something with it...
[code=:0]var found = go.GetComponent();
Simple.
I've packaged up my Visual Studio 2012 solution for you to play with. It contains the basic implementation detailed here and some simple MSTest-based unit tests.
Have fun.
Could you post this an article?