Jump to content

  • Log In with Google      Sign In   
  • Create Account






Creating Unity-like GameObjects in C#

Posted by Alex Hopkins, in C#, DirectX 11, Engine, Unity3D 28 August 2012 · 887 views

unity unity3d c# game object GameObject instantiate
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<GameObject> 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<T>(Vector3 Position, Vector3 Rotation)
		{
			var newGO = PInstantiate<T>();
			GameObject go = newGO as GameObject;
			go.TranslateTo(Position);
			go.RotateTo(Rotation);
			return newGO;
		}
		private static T PInstantiate<T>()
		{
			var constructorInfo = typeof(T).GetConstructor(new Type[] { });
			var newGameObject = (T)constructorInfo.Invoke(new object[] { });
			return newGameObject;
		}





July 2014 »

S M T W T F S
  12345
6789101112
13141516171819
202122232425 26
2728293031  

Recent Comments

PARTNERS