Search
Close this search box.

Tutorial 4: Unity Programming (Part 1) | Unity 2D

  1. Generating Idea & Game Design (characters, scenes and stuff)
  2. Creating Unity Project – GIT
  3. Animation in Unity
  4. Unity Programming(Part 1)
  5. How to make money from game
  6. Publishing game on app stores (Microsoft Windows phone, windows store, android)
  7. Marketing Tactics
  8. What’s next

This unity 2d tutorial is connected to previous tutorial series. This is unity programming tutorial, we shall be looking at how to make scrolling background for the 2d game in unity, Adding background music, switching scenes, button click event in unity, will work on creating another scene in which we will program sky, background buildings, will look on tutorial how to add hurdles in unity 2d game and finally look at how to enter scores in unity 2d game.

Scrolling Background for 2D game in unity

In previous tutorial, we added material (holding texture) to the quad but it was not animated background. In this unity 2d tutorial, we’ll be endlessly animating background in unity 2d game. Basically this is called, unity parallax scrolling background. In the unity project, right click on script folder > create > C# Script and name it bgAnim.

Drag this script over quad object. Double click the script and let it open in MonoDevelop. Once Script is loaded, you will see two methods (start and update)

  • void start() – Anything inside this method, will be executed only once at the start of game.
  • void update() – Anything inside this method, will be executed at every frame during game play.

Before start() method set these variables:

// Variables to control the speed of background movement
	public float speed = 0.001f;
	private float position = 0;

Inside the Update method enter the following code:

position += speed;
		if (position > 1.0f)
			position -= 1.0f; // Resets position value to start
		renderer.material.mainTextureOffset = new Vector2(position, 0);

Explanation: Previously we added background, which was a material holding texture on quad object. Basically, in the above code,  at every frame update, position of material is being incremented by 0.01 and when its position value exceeds 1(means its off screen) then it is reset back to 0, this process continues and it looks like parallax infinitely scrolling background. Last line is simply accessing the material’s texture on quad. I have provided x and y value for texture offset, it changes at every frame and then you get the unity 2d scorlling background.

Issue: You may see clouds leaving trail behind while in play mode.

Fix: Goto Textures folder in your unity project > select clouds.jpg > In inspector, make following changes:

  • Texture type: Texture
  • Alpha from grayscale: uncheck
  • Wrap Mode: repeat
  • Filter Mode: Bilinear
  • Aniso Level: 1
  • Click Apply and run the game, you will see texture animating over quad.

Background Music

Right click on sounds folder > Import new asset > select sound (below is sound I used, you can download following for free if you want)

Once sound is imported into project, drag it to the quad object in hierarchy. You will now see audio source in quad, expand 3D sound settings in it and select Volume Rolloff > Linear Roll off. Play the game, you will hear background music.

Switching Scene

Now I will make “Go” button clickable and then switch to another scene. Basically this part is about GUI buttons but this tutorial is simpler approach to make clickable buttons in unity 2d. If you want to to use some plugin for unity then you can go for NGUI icon-external-link  plugin. But here I will not use that plugin. Lets make a button.

  • Create a new C# file in scripts folder and name it “loadScene.cs” then attach this script to go button(drag and drop over go button) in hierarchy. Open loadScene.cs script and enter following code inside class braces:
    public float buttonPressAmount = 0.12f;
    
    void OnMouseDown ()
    {
    	// play sound on button click
    	audio.Play ();
    	// press button to specified amount
    	transform.position = new Vector2 (transform.position.x, transform.position.y - buttonPressAmount);			
    }
    
    void OnMouseUp ()
    {
    	// release button back to its original position
    	transform.position = new Vector2 (transform.position.x, transform.position.y + buttonPressAmount);
    	// load game level named "Game"		
    	Application.LoadLevel ("Game");
    }
  • Select go button in hierarchy, in its inspector, click Add Component > Physics > Box Collider. By doing this unity will record clicks.
  • Now create another scene from File > New Scene. A dialog box will appear click on save and you will get new scene.
  • Save the newly created scene and name it “Game”.
  • Goto File > Build Settings > click Add Current. This will add current scene to build settings.
  • Load Home scene from project and repeat above step so that it can also be added to build settings.
  • Line 5-6, play sound when button is clicked, but we don’t have click sound yet. Download here (right click & save as)
  • Import audio clip in project, that you want and then drag & drop it to go button. You will get audio source component in inspector.
  • In audio source, uncheck play on awake and under 3D sound settings > volume rolloff > select Linear Rolloff
  • Play game, you will now hear background music, when you click on go button, it will press and play sound and then move to next scene.

Skipped: Main Menu (will do it later)

Creating Game Scene in unity 2D game

Sky:

Will reuse sky(Animating background section above) which is a material on quad object, like this:

  • Right now you are in Home scene. In project, right click on prefab folder > Create > Prefab
  • Drag and drop Quad from hierarchy on to Prefab
  • Open game scene, drop the newly created prefab in the Game scene and adjust its scale if required.

Building:

You have the bg2.png (building image)file in your texture folder.

  • Click on bg2.png and change its properties like we have done earlier in this tutorial above
  • Create a quad in hierarchy and name it building.
  • Create a new material in materials folder and drag it to the building(newly created quad) object
  • Now building object has a material component, drag and drop bg2.png image on to material in inspector of building
  • Change material of building: shader > Unlit > Transparent
  • Resize the building object in scene by holding shift, so that it covers the bottom portion of scene
  • Change its speed to 0.002f this is what I like. You can adjust speed in inspector under bgAnim script.

Hurdle Instantiator:

You’ve hurdles-n-bonuses.png image in texture folder. click on it and slice all sprite like we did in previous tutorial.

  • Open the Game scene. Create an empty game object and name it “hurdle Instantiator”.
  • Drop the sliced green cylinder on “hurdle Instantiator”. So that green cylinder becomes child of hurdle Instantiator.
  • In the inspector of green cylinder: click Add Component > Physics 2D > Box Collider 2d.
  • In the inspector of green cylinder: click Add Component > Physics 2D > Rigid body 2d. Change its gravity scale to zero so that it doesn’t fall.
  • Note: Make sure that position z of green cylinder and hurdle instantiator is 0.
  • Duplicate green cylinder in hierarchy, so that “hurdle instantiator” has two children green cylinders and then adjust their sizes and position so that they looks like this:
  • Create a new C# script in scripts folder and name it hurdleStarter.cs and the following code to it then attach it “hurdle Instantiator” object:
    using UnityEngine;
    using System.Collections;
    
    public class hurdleStarter : MonoBehaviour
    {
    	public GameObject hurdlePrefab;
    	public int timeManager;
    	public GUIText scoreText;
    	
    	void Update ()
    	{
    		transform.position = new Vector3 (12f, 4f, -4);
    		timeManager = (int)Time.timeSinceLevelLoad;
    		scoreText.text = timeManager.ToString (); 
    
    		if (!IsInvoking ("makeHurdle"))
    			Invoke ("makeHurdle", 2.5f);
    	}
    	
    	void makeHurdle ()
    	{
    		Instantiate (hurdlePrefab, transform.position = new Vector3 (9f, Random.Range (3f, -3f), -4), transform.rotation);
    	}
    }

     Explanation: Line 6-8 says, get a prefab(will create in a moment), an integer and get a GUI text(will create in a moment) to show scores. Line 12 say, move “hurdle instantiator” object away from scene because It has to instantiate hurdles(will create in a moment) automatically from a specific point outside of screen so that it seems like they are coming from right and going left.  Line 13-14 says, get the time since Game scene is loaded, convert it to integer type then assign it to time manager. TimeManager then converts to string type and assigns its value to text property of GUItext(will create in a moment). Line 16-17, condition checks if “makeHurdle” method is pending to execute? If not pending, then execute it after 2.5 seconds. Since this condition is in update function, so it will check this at every frame.  Line 20 says, create an instance of “hurdle” object(will provide in a moment) at specified axis i.e Vector3(x,y,z). Though x and z axis are simple but at y axis I entered a Random.Range function that will generate values according to given lower and upper limit.

Hurdle(Prefab):

This object will be instantiated by hurdle instantiator object defined step above.

  • Duplicate “hurdle instantiator” object in hierarchy and name it “hurdle”.
  • Remove hurdleStarter script from “hurdle” object.
  • Create a new c# script, name it hurdleMover.cs and assign it to “hurdle” object in hierarchy. Enter the following code in hurdleMover file:
    using UnityEngine;
    using System.Collections;
    
    public class hurdleMover : MonoBehaviour
    {
    	public float hurdler = 0.07f;
    
    	void Update ()
    	{
    		transform.Translate (Vector3.left * hurdler, Space.World);
    		Destroy (this.gameObject, 8);
    	}
    }
    

    Explanation: In update function, translating hurdle object from right to left and destroying it after 8 seconds. It was instantiated by makeHurdle method in hurdleStarter script which was assigned to hurdle Instantiator object.

  • Create a new prefab in prefab folder.
  • Drag & drop hurdle object to newly created prefab.
  • Goto hurdle instantiator: Inspector > Hurdle Starter (script) > click on circle at the very right side of hurdle field and select the prefab you just created.

GUI Text:

It will show time elapsed since scene load.

  • In hierarchy, click Create > Gui Text
  • Right click on fonts folder and import this font.
  • Click in the font section of gui text and select the newly imported font. Resize and reposition as desired.
  • Click hurdle Instantiator: Inspector > Hurdle Script (script) >  click on circle at the very right side of “Score Text” and select the Gui Text you just created.

Finally, play the game and you will see animating clouds, buildings, randomly generated cylinders and time on the screen. Tutorial to be cont…

Download project file at git hub:

Hope you like it. Please share my work. Wait for next tutorial.

Previous-Chapter-Button-Animation-in-unity

//

Leave a Reply

Your email address will not be published. Required fields are marked *

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar is an expert Web Developer, SEO specialist, and Graphic Designer. Hafiz Faraz is an expert in WordPress design and development. Hire on Upwork | Hire on Fiverr