Entry 7: Tiling the Stages

When it comes to endless running, tiling mechanism is pretty crucial

Tutorial used:

YouTube. (2018). Unity Endless Tutorial • 0 • Introduction [Tutorial][C#]. [online] Available at: https://www.youtube.com/watch?v=7jdL5538bEo&index=1&list=PLLH3mUGkfFCXps_IYvtPcE9vcvqmGM pRK [Accessed 30 Jan. 2018].

This video show how tiling in Unity3D is made.



So what it does is it spawns the prefab randomly on the z-axis.
By following the tutorial, I'm able to get the tiling function to work.

Here's the code:




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

public class tileManager : MonoBehaviour {

    public GameObject[] tilePrefabs;

    private Transform playerTransform;
    public float spawnZ = -1000.0f;
    public float tileLength = 1900.0f;
    public int amnTilesOnScreen = 3;
    public float safeZone = 1000.0f;
    private int lastPrefabIndex = 0;

    public List<GameObject> activeTiles;

// Use this for initialization
void Start () {
        activeTiles = new List<GameObject>();
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;

        for(int i = 0;i < amnTilesOnScreen; i++)
        {
            if (i < 3)
                SpawnTile(0);
            else
                SpawnTile();
        }


    }

// Update is called once per frame
void Update () {

        if(playerTransform.position.z - safeZone> (spawnZ - amnTilesOnScreen * tileLength))
        {
            SpawnTile();
            DeleteTile();
        }


}

    void SpawnTile(int prefabIndex = -1)
    {
        GameObject go;
        if (prefabIndex == -1)
            go = Instantiate(tilePrefabs[RandomPrefabIndex()] as GameObject);

        else
            go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;

        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward * spawnZ;
        spawnZ += tileLength;

        activeTiles.Add(go);
    }

    void DeleteTile()
    {
        Destroy(activeTiles[0]);
        activeTiles.RemoveAt(0);
    }

    private int RandomPrefabIndex()
    {
        if (tilePrefabs.Length <= 1)
            return 0;

        int randomIndex = lastPrefabIndex;
        while(randomIndex == lastPrefabIndex)
        {
            randomIndex = Random.Range(0, tilePrefabs.Length);

        }

        lastPrefabIndex = randomIndex;
        return randomIndex;
    }

}






Then I've created a gameObject that stores the code. Then from there, I can start creating some obstacle courses and make it into prefabs.



All I need to do now is to adjust where the prefabs going to spawn so that the coming prefab wouldn't clip with other prefab





Comments

Popular posts from this blog

Entry 9: Post-Processing in Unity