I'm trying to make my Unity mobile game Difficulty options button selections (Easy/Medium/Hard) function to change the spawn rate for enemy ai. For example, clicking on Medium should trigger spawn 2x as much ai across all levels/scenes.
I have the buttons working according to Console but the difficulty Button script is not communicating with the Spawn script properly since selecting a difficulty level is not influencing spawn rate.
Does anyone see what I'm missing? Have spent lots of time on this but no luck.
Difficulty Button Script:
public class DifficultyButton : MonoBehaviour
{
private Button button;
private RandomSpawn randomSpawn;
public int difficulty;
// Start is called before the first frame update
void Start()
{
button = GetComponent<Button>();
button.onClick.AddListener(SetDifficulty);
randomSpawn = GameObject.Find("Random Spawn").GetComponent<RandomSpawn>();
}
//click on diff buttons n Console will show they were clicked
void SetDifficulty()
{
Debug.Log(gameObject.name + " was clicked");
}
}
Spawn Script:
public class RandomSpawn : MonoBehaviour
{
public GameObject prefab1, prefab2, prefab3, prefab4;
public float spawnRate = 2f;
private float nextSpawn = 0f;
private int whatToSpawn;
public bool isGameActive;
public void StartGame(int difficulty)
{
isGameActive = true;
spawnRate /= difficulty;
}
void Update()
{
if (Time.time > nextSpawn) { //if time has come
whatToSpawn = Random.Range(1, 6); // define random value between 1 and 4 (5 is exclusive)
Debug.Log(whatToSpawn); //display its value in console
switch (whatToSpawn) {
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Instantiate(prefab2, transform.position, Quaternion.identity);
break;
case 3:
Instantiate(prefab3, transform.position, Quaternion.identity);
break;
case 4:
Instantiate(prefab4, transform.position, Quaternion.identity);
break;
}
nextSpawn = Time.time + spawnRate;
}
}
}
Here's a pic of my difficulty button setup on Hard in the Inspector