Sign in to follow this  
  • entries
    7
  • comments
    5
  • views
    14639

Creating Unity-like GameObjects in C#

Sign in to follow this  
Alex Hopkins

1606 views

One of the things I like most about Unity3D, apart from the rich editor environment, is the way the GameObject class is so rich. It provides access to many useful methods and exposes the things common to all objects within the game, such as position and rotation.

I wanted to emulate something similar for my C# DX11 engine, so I came up with this approach.


public abstract class GameObject
{
public Vector3 Position;
public Vector3 Rotation;
public static int UUIDCount = 0;
public static List GameObjects;
public int UUID;
}



This is a very stripped-bare version of the class but it demonstrates that all GameObjects will have a Position and Rotation property (along with associated methods).

The UUIDCount is a static int that is incremented whenever a new GameObject is instantiated. This is applied to the UUID field of that instance, giving each GameObject a unique identifier. (No account is currently made for destroyed objects freeing up UUIDs)

The instantiated GameObject also adds itself to a static list of GameObjects. This allows them to stay in scope even if they fall out of scope in the code that generated them, just like Unity. This list will later be iterated and each GameObject can have certain methods called, such as Update (to call Update on any attached scripts!). Any visual editors I make will also be able to list the active GameObjects (handy for debugging).

The Instantiate() method of the GameObject is static and templated, so it can be used by any derived class.


public static T Instantiate(Vector3 Position, Vector3 Rotation)
{
var newGO = PInstantiate();
GameObject go = newGO as GameObject;
go.TranslateTo(Position);
go.RotateTo(Rotation);
return newGO;
}
private static T PInstantiate()
{
var constructorInfo = typeof(T).GetConstructor(new Type[] { });
var newGameObject = (T)constructorInfo.Invoke(new object[] { });
return newGameObject;
}
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now