Making a 2D Game in unity part-2

Create an empty gameobject from the hierachy. and name it Tile_1. we will make some tile and genarate them randomly in the right to make endless path for our player with an endless tile generating script.
Select the gameobject and make this setting.

1.png

Now take two floor image and set it as child object of Tile_1. Now we need to add collider so that it can detect collision. add box collider2D or polygon collider. make sure the collider matches the area of the image.

2.PNG

Now take the background image and set it with the Tile_1. adjust the z axis position to fit every frame perfectly.

3.PNG

You may add other things in the frame. using multiple tile will be great. but for now I will leave it like this and save it as a prefab. Just drag the game object to a folder in project window and it will be saved as a prefab. Making a prefab gives you the setting to use the game object in any scene any time.

now we are going to make a script. we do not need the tiles we left behind when we are playing the game. This script will detect the player position and destroy the game object when the player leave it. Make a new c# script and name it "destroyTile". copy and paste this script to your script.

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class destroyTile : MonoBehaviour { public float dis; GameObject player; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag ("Player"); }

// Update is called once per frame
void Update () {
    if(player.transform.position.x>transform.position.x+dis)
    {
        Destroy (gameObject);
    }
}

}

save it and go to unity. This is the component we just made.

4.PNG

set a value like 2* tile length.

we need to attach this script with every tiles.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?