Search code examples
c#unity-game-enginegame-developmentrunner

Spawning an infinite amount of prefabs


I have been trying to learn Unity 3D by creating a simple runner game. The game was spawning a simple road from asset store. I have decided to add some obstacles to that road and make a prefab from it, but when I added that prefab to an array from which Unity takes prefabs to instantiate them and ran the game no prefabs were instantiated. Here is my code:

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

public class TileManager : MonoBehaviour
{

public GameObject[] amountOfPrefabs;
private Transform playerTransform;
private float spawnZ = 0.0f;
private float tileLength = 30.0f;
private int amnTileOnScreen = 7;
// Use this for initialization
void Start()
{
    playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
    for (int i = 0; i < amnTileOnScreen; i++)
    {
        SpawnTile();
    }
}

// Update is called once per frame
void Update()
{
    if (playerTransform.position.z > (spawnZ - amnTileOnScreen * tileLength))
    {
        SpawnTile();
    }
}

private void SpawnTile(int prefabIndex = -1)
{
    GameObject go;
    go = Instantiate(amountOfPrefabs[0]) as GameObject;
    go.transform.SetParent(transform);
    go.transform.position = Vector3.forward * spawnZ;
    spawnZ += tileLength;
}
}

Please, help me.


Solution

  • It seems that something was wrong with Unity3D, because when I created the same GameObject with the same script it started working