Hello there guys,
I am having trouble with some Ball Spawning code i was trying to create while watching course.
I wanted to make this spawn random types of ball prefabs at certain percentage chances. AT random locations. I know…
I got everything almost working but when i bring the two ideas together they will not work but separately they do. I think the problem lies in how i am instantiating and trying to use my GetRandomSpawn method.
Is this possible? How would i split this up into multiple methods and achieve the same result?
PROBLEM LINE OF CODE: Instantiate(BallsToSpawn[GetRandomSpawn],new Vector3(xBallPos,yBallPos, 1), Quaternion.identity);
CODE:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallGeneration : MonoBehaviour
{
public GameObject Ball;
[SerializeField] public int totalBallCount = 10;
public float xBallPos, yBallPos;
[SerializeField] public int ballCount;
[SerializeField] float[] percentagesToSpawn;
[SerializeField] GameObject[] BallsToSpawn;
Transform spawnPoint;
void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.tag == "Ball")
{
Debug.Log("Void Hit");
ballCount -= 1;
}
}
void Start()
{
StartCoroutine(BallDrop());
IEnumerator BallDrop()
{
while (ballCount < totalBallCount)
{
xBallPos = Random.Range(-7.8f, 9f);
yBallPos = Random.Range(5.45f, 7f);
Instantiate(BallsToSpawn[GetRandomSpawn],new Vector3(xBallPos,yBallPos, 1), Quaternion.identity);
ballCount += 1;
yield return new WaitForSeconds(.7f) ;
}
}
}
public IEnumerable<int> GetRandomSpawn()
{
float random = Random.Range(0f, 1f);
float numForAdding = 0;
float total = 0;
for (int i = 0; i < percentagesToSpawn.Length; i++)
{
total += percentagesToSpawn[i];
}
for (int i = 0; i < BallsToSpawn.Length; i++)
{
if(percentagesToSpawn[i] / total + numForAdding >= random)
{
yield return i;
}
else{
numForAdding += percentagesToSpawn[i] / total;
}
}
}
}