Unity – Text Element Unity’s inbuilt text UI is a great starting point for learners to get into designing UI, even if it tends to be overshadowed by more powerful and efficient community-built assets. For our purpose, the vanilla Text element is more than sufficient to get started. Text being a distinct UI element of its own is primarily due to the dynamism of that element. For example, printing the player’s current score to the screen requires the numeric value of the score to be converted to a string, generally through the .toString() method, before it is displayed. To insert a Text UI element, go to the Scene Heirarchy, Create → UI → Text. A new Text element should show up in your Canvas region. If we have a look at its properties, we will see some very useful options. What is most significant of all, however, is the Text field. You can type out what you want the text box to say in that field, but we want to go a step further than that. To change the font of the text, you must first import the font file from your computer into Unity, as an Asset. A font does not need to be actively attached to anything in the scene, and it can be directly referenced from the Assets. The Text element can be accessed through scripting as well; this is where the importance of dynamic UI comes in. Instead of the console, outputting how many times the button has been pressed, as in the previous chapter; let us actually print it out on the game screen. To do so, we will open up our ButtonBehaviour script from the previous lesson, and make a few changes to it. using UnityEngine; using UnityEngine.UI; public class ButtonBehaviour : MonoBehaviour { int n; public Text myText; public void OnButtonPress(){ n++; myText.text = “Button clicked ” + n + ” times.”; } } The first change we did was to add a new namespace reference. This reference is used to work with Unity’s UI components, and so we add the using UnityEngine.UI line. Next, we create a public Text variable, where we can drag and drop our Text UI element onto. Finally, we access the actual text this UI element contains using myText.text. If we save our script, we will now see a new slot for the Text UI element in our ButtonManager. Simply drag and drop the gameObject containing that Text element onto the slot, and hit the Play button.
Category: unity
Unity – The Button In this chapter, we will earn how to insert UI elements into our scene and go about working with them. Let us start off with a Button. To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well. Remember that in Overlay rendering mode, which is the default mode, the size of the Canvas is independent of the size of the camera. You can test this by clicking on the Game tab. If you play the scene, you will notice the button already has some standard functionality such as detecting when the mouse is hovering over it, and changing color when pressed. A Button requires functionality to be actually useful in the UI. This functionality can be added through its properties. Let us create a new script, and call it ButtonBehaviour. public class ButtonBehaviour : MonoBehaviour { int n; public void OnButtonPress(){ n++; Debug.Log(“Button clicked ” + n + ” times.”); } } We have made a simple method that logs how many times we have hit the button. Note − This method has to be public; it will not be noticed by the Button’s functionality otherwise. Let us create an empty GameObject and attach this script to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting. Now, go into the Button’s properties, and find the OnClick() property. Hit the + icon on the bottom tab, and a new entry should show up in the list. This entry defines what object the button press acts on, and what function of that object’s script is called. Because of the event system used in the button press, you can trigger multiple functions simply by adding them to the list. Drag and drop the empty GameObject, which contains the ButtonManager script we created, onto the None (Object) slot. Navigate the No Function dropdown list, and look for our OnButtonPress method. (Remember that it can be named anything you want, OnButtonPress is simply a standardized naming convention.) You should find it in the ButtonBehaviour section. If you play the game now, you can test the button and surely enough, the console prints out how many times you have pressed the button.
Unity – Starting with UI In this section, we will learn about the design process for User Interface or UI elements in Unity. This includes the base setup, as well as an overview of the common elements that ship with Unity. The workflow for designing UI in Unity follows a slightly different path than the one we have been going through so far. For starters, UI elements are not standard GameObjects and cannot be used as such. UI elements are designed differently; a menu button which looks correct in a 4:3 resolution may look stretched or distorted in a 16:9 resolution if not set up right. UI elements in Unity are not placed directly onto the scene. They are always placed as children of a special GameObject called the Canvas. The Canvas is like a “drawing sheet” for UI on the scene, where all UI elements will render. Creating a UI element from the Create context menu without an existing Canvas will automatically generate one. Let us now look at the Canvas GameObject to know about the additional new components − The Rect Transform at the top appears to have many new properties that a standard GameObject’s Transform does not have. This is because while a normal GameObject’s Transform describes an imaginary point in 3D space, a RectTransform defines an imaginary rectangle. This means we need additional properties for defining exactly where the rectangle is, how big it is and how it is oriented. We can see some standard properties of a rectangle like the Height and Width, as well as two new properties called Anchors. Anchors are points that other entities can “lock” onto in the Canvas. This means that if a UI element (say, a button) is anchored to the Canvas on the right, resizing the Canvas will ensure that the Button is always on the relative right of the Canvas. By default, you will not be able to modify the shape of the canvas area, and it will be a comparatively gigantic rectangle around your scene. Next is the Canvas Component. This is the master component that holds a couple of universal options as to how the UI is drawn. The first option we see is the Render Mode. This property defines the method that is used to draw the Canvas onto the game’s view. We have three options in the dropdown list. Let us learn about the options in our subsequent sections. Screen Space – Overlay This mode is the most standard for menus, HUDs and so on. It renders UI on top of everything else in the scene, exactly how it is arranged and without exception. It also scales the UI nicely when the screen or game window size changes. This is the default Render Mode in the Canvas. Screen Space – Camera Screen Space – Camera creates an imaginary projection plane, a set distance from the camera, and projects all UI onto it. This means that the appearance of the UI in the scene depends heavily on the settings used by the camera; this includes perspective, field of view, and so on. World Space In World Space mode, UI elements behave as if they were normal GameObjects placed into the world. They are similar to sprites, however, so they are typically used as part of the game world instead of for the player, like in-game monitors and displays. Because of this nature, you can directly modify the values of the Canvas RectTransform in this mode. The Canvas Scaler is a set of options that lets you adjust the scale and appearance of the UI elements in a more definitive way; it allows you to define how UI elements resize themselves when the size of the screen changes. For example, UI elements can remain the same size regardless of as well as in ratio to the screen size, or they can scale according to a Reference Resolution. The Graphics Raycaster deals primarily with raycasting (link to Unity Documentation for Raycasting) the UI elements and ensuring user-initiated events like clicks and drags work correctly.
Understanding Prefabs and Instantiation Instantiating and destroying objects is considered very important during gameplay. Instantiating simply means bringing into existence. Items appear or “spawn” in the game, enemies die, GUI elements vanish and scenes are loaded all the time in-game. Knowing how to properly get rid of unneeded objects and how to bring in those you do then becomes even more essential. Let us first understand what prefabs are. Prefabs are considered important to understand how Instantiation works in Unity. Prefabs are like blueprints of a GameObject. Prefabs are, in a way, a copy of a GameObject that can be duplicated and put into a scene, even if it did not exist when the scene was being made; in other words, prefabs can be used to dynamically generate GameObjects. To create a prefab, you simply have to drag the desired GameObject from your scene hierarchy into the project Assets. Now, to instantiate a GameObject, we call the Instantiate() method in our script. This method, defined in MonoBehaviour, takes in a GameObject as a parameter, so it knows which GameObject to create/duplicate. It also has various overrides for changing the newly instantiated object’s transform, as well as parenting. Let us try instantiating a new hexagon whenever the Space key is pressed. Create a new script called Instantiator and open it up. In the Update method, type in the code given below. Here, we are using the GetKeyDown method of the Input class to check if the player pressed a specific button during the last frame. Since we want it to keep checking, we put it in Update, which runs 60 times per second. The GetKeyDown method returns true if the key specified by the KeyCode enum (which lists all possible keys on a standard keyboard) is pressed in that frame. public class Instantiator : MonoBehaviour { public GameObject Hexagon; // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Space)) { Instantiate(Hexagon); } } } The public GameObject declaration at the top creates a slot similar to the one we made for the Rigidbody2D in our previous lessons. This slot only accepts prefabs (in editor time) and gameObjects (in runtime), however. Save the script, and let it compile. Once it is done, create a new, empty GameObject by going to your object hierarchy right-click menu, and selecting Create Empty. Name this Object something recognizable such as Instatiator Object and attach our newly created script to it. In the slot that shows up for the GameObject, drag in the prefab we created. If we run the game now, pressing the Spacebar will create a new Hexagon object identical to the one we used to create the prefab. You can see each hexagon being created in the object hierarchy. The reason you cannot see them show up in the game is because for the time being, they are all being created exactly one over the other. In our next lesson, we will understand the concept of object destruction.
Unity – Understanding Collisions Collisions in Unity are separated from the actual Sprite itself, attached as separate components and are calculated on their own. Let us now learn the cause behind this. Everything in your game is a GameObject. Even the individual tiles that make up your level are GameObjects by themselves. When we consider every component as a GameObject, we realize that there could be thousands of GameObjects in a scene, interacting with each other in some way. You can imagine that if Unity added collisions to every single GameObject, it would be impractical for the engine to calculate collisions for every single one of them. We will go ahead and add a simple “wall” that our player character can collide against. To do so, create another sprite and scale it up using the Rect tool. We will also give it a red color through the Color property in the Sprite Renderer component. Now, go to Add Component in the Inspector, and type in “Box Collider 2D”. Click the first component that shows up, and a new component should appear. You will see a bright green line on the perimeter of your GameObject. This is the collision boundary. It is what defines the actual shape of the collidable objects. Repeat the same with our movable GameObject as well. Of course, collisions in Unity are not limited to simply boxes. They can range in a variety of shapes and sizes, and are not necessarily replicas of the object’s parameters. They can also take on polygonal shapes. It is not uncommon to see developers and designers use approximate shapes in their collision boundaries to simplify their colliders and avoid unnecessary calculations for the engine. We will learn how to create different shapes and sizes with our colliders soon. Now that we have our collision boundaries in place, hit play and see it in action. You will notice that our movable object is not behaving normal. We will discuss the behaviour of the object in our subsequent chapter.
Unity – Rigidbodies and Physics The main issue with the collisions in the last chapter was with the code. We will now modify the values of the GameObject’s position directly. We are simply adding a value to the position, if the player is pressing a key. We need a way to make the player move in such a way that it reacts properly to boundaries and other GameObjects. To do so, we need to understand what rigidbodies are. Rigidbodies are components that allow a GameObject to react to real-time physics. This includes reactions to forces and gravity, mass, drag and momentum. You can attach a Rigidbody to your GameObject by simply clicking on Add Component and typing in Rigidbody2D in the search field. Clicking on Rigidbody2D will attach the component to your GameObject. Now that it is attached, you will notice that many new fields have opened up. With the default settings, the GameObject will fall vertically down due to gravity. To avoid this, set the Gravity Scale to 0. Now, playing the game will not show any visible difference, because the GameObject does not have anything to do with its physics component yet. To solve our problem, let us open our code again, and rewrite it. public class Movement : MonoBehaviour { public float speed; public Rigidbody2D body; // Update is called once per frame void Update() { float h = Input.GetAxisRaw(“Horizontal”); float v = Input.GetAxisRaw(“Vertical”); body.velocity = new Vector2(h * speed, v * speed); } } We can see that we create a reference to a Rigidbody2D in the declarations, and our update code works on that reference instead of the Object’s transform. This means that the Rigidbody has now been given the responsibility of moving. You may expect the body reference to throw NullReferenceException, since we have not assigned anything to it. If you compile and run the game as is, you will get the following error on the bottom left of the editor To fix this, let us consider the component created by the script. Remember that public properties create their own fields in Unity, as we did with the speed variable. Adjust the speed to a higher value, around 5, and play the game. Your collisions will now work correctly!
Unity – GameObject Destruction The destruction of GameObjects is as important as the instantiation. In this chapter, we will learn how to destroy the GameObjects. Fortunately, destroying GameObjects is as easy as it is creating them. You simply need a reference to the object to be destroyed, and call the Destroy() method with this reference as a parameter. Now, let us try to make 5 hexagons which will destroy themselves when an assigned key is pressed. Let us make a new script called HexagonDestroyer and open it in Visual Studio. We will start by making a public KeyCode variable. A KeyCode is used to specify a key on a standard keyboard, and the Input class in its methods uses it. By making this variable public, as we did with Rigidbody and Prefabs previously, we can make it accessible through the editor. When the variable is made public, we need not hardcode values such as “KeyCode.A” into the code. The code can be made flexible with as many objects as we want. public class HexagonDestroyer : MonoBehaviour { public KeyCode keyToDestroy; // Update is called once per frame void Update () { if (Input.GetKeyDown(keyToDestroy)) { Destroy (gameObject); } } } Observe how we used the variable named “gameObject” (small g, capital O) in the method. This new gameObject variable (of type GameObject) is used to refer to the gameObject this script is attached to. If you attach this script on multiple objects, they will all react the same way whenever this variable is involved. Do not get confused between the two, however. GameObject with a capital G and O is the class that encompasses all GameObjects and provides standard methods like Instantiate, Destroy and methods to fetch components. gameObject with a small g and capital O is the specific instance of a GameObject, used to refer to the gameObject this script is currently attached to. Let us now compile our code, and head back to Unity. Now, we will create a new hexagon sprite, and attach our script to it. Next, right-click the gameObject in the hierarchy and select Duplicate. A new sprite is created in the hierarchy; you should use the Move tool to reposition it. Repeat the steps to create similar hexagons. Click on each of the hexagons and look at their script components. You can now set the individual keys so that a GameObject destroys itself when that key is pressed. For example, let us create 5 hexagons, and set them to destroy when the A, S, D, F and G keys are pressed. You can set the same key on multiple hexagons, and they will all destroy themselves simultaneously when the key is pressed; this is an example of the use of the gameObject reference, which you can use to refer to individual objects using the script without having to set them individually. The same key can be set on multiple hexagons, and they will all destroy themselves simultaneously when the key is pressed; this is an example of the use of the gameObject reference, which you can use to refer to individual objects using the script without having to set them individually. It is important to understand that destroying a GameObject does not mean an object will shatter or explode. Destroying an object will simply (and immediately) cease its existence as far as the game (and its code) is concerned. The links to this object and its references are now broken, and trying to access or use either of them will usually result in errors and crashes.
Unity – Basic Movement Scripting In this lesson, we will write code that makes a gameObject move up, down, left and right based on the user’s input. This should help us understand the workflow of Unity scripting more easily. Remember that every GameObject has at least one component − Transform. What is special is that the Transform of a gameObject also shows up as variables in the scripting side of Unity so we can modify it via code. This is not restricted to the Transform either; all components in Unity have properties, which are accessible through variables in scripting. Let us start with our movement script. Create a new script, and name it “Movement”. Now, open the script and you should see the same stuff you saw in the last lesson. Let us create a public float variable named speed. Making a variable public in Unity has a great advantage − The variable shows up as a modifiable field inside the editor, so you don’t have to manually adjust the values in code. public class Movement : MonoBehaviour { public float speed; } If we save this script without touching the other methods, it should compile in Unity. (You can see when it is compiling by the icon in the bottom right corner.) Next, drag and drop the script from the Assets onto the GameObject. If you do it correctly, this is what you should see in the GameObject’s properties − Since the speed value is adjustable and need not be changed in code all the time, we can use update() method instead of start(). Let us now consider the objectives for the Update method − Check for the user input. If there is a user input, read the directions of input. Change the position values of the object’s transform based on its speed and direction. To do so, we will add the following code − void Update() { float h = Input.GetAxisRaw(“Horizontal”); float v = Input.GetAxisRaw(“Vertical”); gameObject.transform.position = new Vector2 (transform.position.x + (h * speed), transform.position.y + (v * speed)); Let us now discuss the code in breif. First of all, we make a floating point variable named h (for horizontal), and its value is given by the Input.GetAxisRaw method. This method returns -1, 0 or 1 depending on which key the player has pressed on the up/down/left/right arrows. The Input class is responsible for getting input from the user in the form of key presses, mouse input, controller input, and so on. The GetAxisRaw method is slightly harder to understand, so we’ll get back to that later. Next, we are updating the position of our gameObject to a new position defined by creating a new Vector2. The Vector2 takes 2 parameters, which are its x and y values respectively. For the x value, we provide the sum of the object’s current position and its speed, effectively adding some amount every frame the key is pressed to its position. Save this script and head back to Unity. Unity will automatically update all scripts once it compiles successfully, so you don’t have to reattach the script again and again. Now that you are done, change the value of the speed in the GameObject’s properties to say 0.8. This is important because a higher value will make the player move too fast. Now, click Play and see your first small game in action! Try pressing the arrow keys and moving around. To stop the game, simply press Play again. You can even adjust the speed in real-time so you do not have to stop and start it all the time. In the next lesson, we will learn about rigidbodies and collisions.
Unity – Custom Collision Boundaries In this chapter, let us learn about custom collision boundaries. We will also learn how to adjust the size and shape of our colliders. Let us start with our Box Collider. The Box Collider (2D) has 4 adjustable sides, and is shaped like a rectangle. In the Collider’s component, click on this box − You will see 4 “handles” show up on the collider. You can drag these handles around to adjust their sizes. For simple shapes, Unity detects the best possible fit for the collider’s shape as well, provided you pick the right one. For example, picking the circle collider on a circle sprite will match it to its radius. For more complex shapes, Unity will try to create the simplest yet most elaborate collider shape. For that, you need to use the Polygon Collider 2D. Try to click on the Edit Collider button and experiment on adjusting the colliders.
Unity Tutorial Job Search Unity is a cross-platform game engine initially released by Unity Technologies, in 2005. The focus of Unity lies in the development of both 2D and 3D games and interactive content. Unity now supports over 20 different target platforms for deploying, while its most popular platforms are the PC, Android and iOS systems. Audience This tutorial is designed for those who find the world of gaming exciting and creative. The tutorials will help the readers who aspire to learn game-making. Prerequisites It is important to have access to machine that meets Unity’s minimum requirements. A prerequisite knowledge of basic C# is required for full understanding of this series.