Tuesday, October 27, 2015

Game objects and components

Let's look on one of the most important concept in the Unity - game objects and components.

Everything we drag&drop (e.g. camera or sprite) on the game scene is called game object. On the C# script level the game object is an instance of the GameObject class (Note that GameObject class is sealed, so you cannot inherit from it). GameObject class does not do much on its own. It is rather a container for specialized classes, which are inherited from class of other type - Component.

For example: If I drag and drop the camera to the scene and I attach a script to it, you will see in the Unity editor something like this:


Camera in Unity editor UI
By dragging the camera to the scene I have created a new game object with several components in it. Let's now edit the script attached to the camera and let's put into its Awake() method following code:
Component[] components = GetComponents();
foreach (Component c in components)
{
   Debug.Log("Compontent: " + c.GetType() );
}
What happens there? The code in the script defines a new class inherited from Component base class. When the game is started the new object of the defined class is automatically instantiated and its instance is attached to the game object container like any other component.The Component class has a method GetComponents(), which returns list of all components of given type, which are attached to the game object to which the component (i.e. object from our script) is attached to. So in the case of camera the above code will create following list of class names prefixed with namespace. Note that the last item in the list is the script class itself:
UnityEngine.Transform
UnityEngine.Camera
UnityEngine.GUILayer
UnityEngine.FlareLayer
UnityEngine.AudioListener
RetroEngine.PixelPerfectCamera

No comments:

Post a Comment