I’m doing my first project based on the flappy bird project, when the tubes are randomly generated there is a space in the middle between them, I want to add coins in random tubes and randomly in the middle of the tubes, can someone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinSpawn : MonoBehaviour
{
GameObject SpawnAreaPipe;
// Use this for initialization
void Start()
{
SpawnAreaPipe = GameObject.FindGameObjectsWithTag("Pipeblank");
SpawnObject = SpawnObjects[Random.Range(0, SpawnAreaPipe.Length)];
Spawn();
}
void Spawn()
{
if (GameStateManager.GameState == GameState.Playing)
{
//random y position
float y = Random.Range(-0.5f, SpawnAreaPipe.Length); //-0.5f, 1f
//GameObject newObject = (GameObject)Instantiate (PlayerPrefab,P1Tile.transform.position,Quaternion.identity);
GameObject go = Instantiate(SpawnObject, this.transform.position + new Vector3(0, y, 0), Quaternion.identity) as GameObject;
}
Invoke("Spawn", Random.Range(timeMin, timeMax));
}
private GameObject SpawnObject;
public GameObject[] SpawnObjects;
public float timeMin = 500f; //0.2f
public float timeMax = 900f; //2f
Ok, first off. My answer here is assuming the Pipeblank gameobjects are being spawned correctly in the correct places. If so, then continue on to step 1. You also need to ensure that what ever is spawning your blanks runs before this script so it will actually find them when it is executed.
Step1, Comment out everything in your current CoinSpawn script. Dont delete it in case you need to bring it back. For now we want to disable all of it though.
Step2, Copy paste the code I have here inside of CoinSpawn. Save the script and go to the unity inspector.
Step3, Drag and drop your coin prefab from the Project Assets into the “coin” field in the inspector.
Step4, Make sure you have “chance” set to the number you want.
Hit Play.
public GameObject[] tubeEmpties;
public GameObject coin;
public int chance = 2; //This is the chance to spawn a coin, higher number means less likely. A 2 means 50percent chance. A 3 means 33.3percent chance.. A 4 means 25percent chance etc. It's currently set to 50percent chance but you are welcome to change it in the inspector on the fly.
private void Start()
{
tubeEmpties = GameObject.FindGameObjectsWithTag("Pipeblank");
for (int i = 0; i < tubeEmpties.Length; i++)
{
int random = Random.Range(0, chance);
//if you use int's with Random.Range, the max will be exclusive (exclusive means it will not include the highest number. There are a lot of reasons to do this but thats not important right now) so you need to subtract one from it to get the actual number which i've already done for you.
if (random == chance -1)
{
SpawnCoin(tubeEmpties*.transform.position);*
}
}
}
private void SpawnCoin(Vector3 emptyPos)
{
GameObject go = Instantiate(coin, emptyPos, Quaternion.identity) as GameObject;
}