I’m trying to write a script that can randomly generate ‘dungeons’ but I have a problem where for lines 25, 31, 37, I get the error message NullReferenceException. I’ve added ‘// HERE’ to where the problem is. Any help would be greatly appreciated!
Here’s the script:
public int openingDirection;
private ComponentTemplate templates;
public bool spawned = false;
// Start is called before the first frame update
void Start()
{
templates = GameObject.FindGameObjectWithTag("Components").GetComponent<ComponentTemplate>();
Invoke("Spawn", 0.1f);
}
// Update is called once per frame
void Spawn()
{
if (spawned == false)
{
if (openingDirection == 1)
{
int rand = Random.Range(0, templates.bottomComponents.Length);
Instantiate(templates.bottomComponents[rand], transform.position, templates.bottomComponents[rand].transform.rotation);
Debug.Log("SpawnBottom");
}
else if (openingDirection == 2)
{
int rand = Random.Range(0, templates.topComponents.Length); // HERE
Instantiate(templates.topComponents[rand], transform.position, templates.topComponents[rand].transform.rotation);
Debug.Log("SpawnTop");
}
else if (openingDirection == 3)
{
int rand = Random.Range(0, templates.leftComponents.Length); // HERE
Instantiate(templates.leftComponents[rand], transform.position, templates.leftComponents[rand].transform.rotation);
Debug.Log("SpawnLeft");
}
else if (openingDirection == 4)
{
int rand = Random.Range(0, templates.rightComponents.Length); // HERE
Instantiate(templates.rightComponents[rand], transform.position, templates.rightComponents[rand].transform.rotation);
Debug.Log("SpawnRight");
}
spawned = true;
}
}
Hello,
well it can’t be much:
GameObject.FindGameObjectWithTag(“Components”) is null
or
GameObject.FindGameObjectWithTag(“Components”).GetComponent() is null
or
templates.top/left/rightComponents is null
or
Length doesn’t exist in templates.top/left/right.
now it’s up to you to know which one is true. I see you ‘if’ a lot so you’re not exactly sure which ‘openingDirection’ is gonna work out, so checking null should be a good reflex anyway.
If templates.bottomComponents.Length is never null, then it has something to do with your declarations of top, left and right OR that openingDirection is never equal to 1
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:
drag it in using the inspector
code inside this script initializes it
some OTHER external code initializes it
? something else?
This is the kind of mindset and thinking process you need to bring to this problem:
Updating the Version Control package from your project resolves the bug.
Project View → Right-click Packages → View in Package Manager → Select Version Control → Update