Since you are new and asked a sensible question, even using code tags (wow such a rare sight
), i’ll give you some working code here.
Approach #1 would be to let it fail if there are no prefabs added to the groups array. For this we use the assert and give it a meaningful text so we know what the hell is going on without the need for digging in the code.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class Spawner : MonoBehaviour
{
public void spawnNext()
{
Assert.IsTrue(groups.Length > 0, "groups.Length must be greater than 0!");
int i = Random.Range(0, groups.Length);
Instantiate(groups[i], transform.position, Quaternion.identity);
}
private void Start() { spawnNext(); }
public GameObject[] groups;
}
Approach #2 would be to simply not spawn anything at all. For this we just leave the spawnNext method when we have nothing in our array.
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public void spawnNext()
{
if (groups.Length == 0) { return; }
int i = Random.Range(0, groups.Length);
Instantiate(groups[i], transform.position, Quaternion.identity);
}
private void Start() { spawnNext(); }
public GameObject[] groups;
}
Approach #3 would be to add a bool return type to the spawnNext method and return false whenever we are not able to spawn anything. In this case having an empty groups array would result in returning false.
using UnityEngine;
using UnityEngine.Assertions;
public class Spawner : MonoBehaviour
{
public bool spawnNext()
{
if (groups.Length == 0) { return false; }
int i = Random.Range(0, groups.Length);
Instantiate(groups[i], transform.position, Quaternion.identity);
return true;
}
private void Start()
{
if (spawnNext() == false)
{
Debug.Log("Was not able to spawn anything!");
}
}
public GameObject[] groups;
}
Please note that there are probably 100² more approaches to this and those 3 just show how you could make your code better/safer/etc. What is ‘best’ is always dependent on the context that code lives in and since you are new to programming, there is no larger context for now, so any of those are fine =)
This attitude is absolutely WRONG. It’s 99.9999999999% your fault and yours alone.
I can’t tell you how much time i wasted in my life as a programmer, thinking “that can’t be my fault”, “this must be a bug in the engine”, etc. In the end it’s most likely the most embarrasing, stupidest, most idiotic little thing that the programmer (you, me, the others here) did wrong. And thats fine, i bet every single person on this forum can related to that feeling.