Hi, episode 8 of mobile game tutorial is available now. In this episode I will show you how to spawn our collectible objects created in previous episodes:
CODE:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectSpawner : MonoBehaviour
{
public GameObject[] objectsToSpawn;
public int dstBetweenObjects;
int lastObjectSpawnedPosition;
public Transform rocketPosition;
// Start is called before the first frame update
void Start()
{
lastObjectSpawnedPosition = 0;
}
// Update is called once per frame
void Update()
{
if (lastObjectSpawnedPosition <= rocketPosition.position.y)
{
SpawnObject();
}
}
public void SpawnObject()
{
Vector2 spawnPos = new Vector2(RandomPosX(), lastObjectSpawnedPosition + dstBetweenObjects);
lastObjectSpawnedPosition = (int)spawnPos.y;
Instantiate(objectsToSpawn[RandomObject()], spawnPos, transform.rotation);
}
public int RandomPosX()
{
int x = 0;
x = Random.Range(-2, 3);
return x;
}
public int RandomObject()
{
int minRndRange = 0;
int maxRndRange = objectsToSpawn.Length; // 0 - 3
int rndValue = Random.Range(minRndRange, maxRndRange);
return rndValue;
}
}