
Coding with components
Components
in Unity are the building blocks of any game; almost everything you will use or apply will end up as a Component
on a GameObject
in a scene. When a GameObject
is selected, you can view each of its Components
from its Inspector.
You will find that you need to access these various components with script. Next we will discuss the various ways on which you can do this.
Accessing components
To reference the components of a GameObject from within your code, you need to use the GetComponent
function. The following shows you examples of how this is achieved:
Rigidbody myScriptRigidBody; void Awake() { var renderer = this.GetComponent<Renderer>(); var collider = renderer.GetComponent<Collider>(); myScriptRigidBody = collider.GetComponent<Rigidbody>(); } void Update() { myScriptRigidBody.angularDrag = 0.2f * Time.deltaTime; }
This way, the Rigidbody
object that we want to affect can simply be discovered once (when the scripts awakes); then, we can just update the reference each time a value needs to be changed instead of discovering it every time.
Referencing a component
Now, it has been pointed out (by those who like to test such things) that even the GetComponent
call isn't as fast as it should be because it uses C# generics to determine what type of component you are asking for (it's a two-step process: first, you determine the type, and then get the component).
However, there is another overload of the GetComponent
function in which, instead of using generics, you just need to supply the type (therefore removing the need to discover it). To do this, we will simply use the following code instead of the preceding GetComponent<>
:
myScriptRigidBody =(Rigidbody2D)GetComponent (typeof(Rigidbody2D));
The preceding code is slightly longer and arguably only gives you a marginal increase, but if you need to use every byte of the processing power, it is worth keeping in mind.
Controlling the hero
A sprite that only stands on the screen isn't going to make much of a game, so we'll add a script to allow the player to move the hero to the left or right. Before we can do that, we need to add a few more components to the character. More specifically, we need to add the Rigidbody2D
component and the BoxCollider2D
component.
The Rigidbody2D
component will allow our character to be manipulated by physics. This will give us the ability to give her a velocity (or speed) value. The BoxCollider2D
component gives us the ability to check to see if she is touching other objects.
Let's add the two components to our character:
- Select the player from either the Hierarchy list or by selecting the sprite in your scene.
- Add a
Rigidbody2D
component by navigating to Add Component | Physics 2D | Rigidbody 2D in the player'sGameObject
inspector. - Set the Gravity Scale parameter to 0 (as we are not using gravity) and check the Freeze Rotation Z checkbox.
- Next, add a
BoxCollider2D
component by navigating to Add Component | Physics2D | Box Collider 2D. - Select Is Trigger. This lets Unity know that we will be using the
BoxCollider2D
to check if the character is touching object rather than stopping it from passing through objects.
This should give you the following view in the inspector:

Tip
If we were making a game that used gravity, the Rigidbody2D
component would allow our character to be affected by gravity. We would also give our character two BoxCollider2D
components. One component to check to see if the character touched other objects (Is Trigger selected) and another to keep our character from passing through other objects (Is Trigger not selected).
To finish off this chapter, add a new C# script and save it as Assets\Scripts\CharacterMovement.cs
. Open the script in the editor and replace its contents with the following script:
using UnityEngine; using System.Collections; public class CharacterMovement : MonoBehaviour{ // RigidBody component instance for the player private Rigidbody2D playerRigidBody2D; //Variable to track how much movement is needed from input private float movePlayerHorizontal; private float movePlayerVertical; private Vector2 movement; // Speed modifier for player movement public float speed = 4.0f; //Initialize any component references void Awake(){ playerRigidBody2D = (Rigidbody2D)GetComponent(typeof(Rigidbody2D)); } // Update is called once per frame void Update () { movePlayerHorizontal = Input.GetAxis("Horizontal"); movePlayerVertical = Input.GetAxis("Vertical"); movement = new Vector2(movePlayerHorizontal,movePlayerVertical); playerRigidBody2D.velocity=movement*speed; } }
The preceding script is fairly basic; it simply has some parameters to control the speed and its movement direction. We will adjust the character's sprite later when we learn to animate her. The update
method checks if the player is controlling the game using the default horizontal keys (left and right) and vertical keys (up and down) and then applies force to move the hero accordingly.
To finish off, add the script to the player's game object by either dragging it to the object in the Hierarchy or navigating to Add Component | Scripts | Character Movement.
Note
You should note that this very simple controller code only uses a keyboard input. We will later discuss how to implement this for touchscreen devices.
If you run the project now by pressing the play button at the top of the screen, you should see our hero on the screen, and using arrows on the keyboard, the character will move around the screen.