As the title says I’m having a problem with ‘NullReferenceException: Object reference not set to an instance of an object’ when putting in the code for the tutorial.
It says that the lines with the problem are: 34, 39, 44, 49
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class RoomSpawner : MonoBehaviour
{
public int openingDirection;
// 1 --> need bottom door
// 2 --> need top door
// 3 --> need left door
// 4 --> need right door
public RoomTemplates templates;
private int rand;
private bool spawned = false;
public float waitTime = 4f;
void Start()
{
Destroy(gameObject, waitTime);
templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomTemplates>();
Invoke("Spawn", 0.5f);
}
void Spawn()
{
if (spawned == false)
{
if (openingDirection == 1)
{
rand = Random.Range(0, templates.bottomRooms.Length);
Instantiate(templates.bottomRooms[rand], transform.position, templates.bottomRooms[rand].transform.rotation);
}
else if (openingDirection == 2)
{
rand = Random.Range(0, templates.topRooms.Length);
Instantiate(templates.topRooms[rand], transform.position, templates.topRooms[rand].transform.rotation);
}
else if (openingDirection == 3)
{
rand = Random.Range(0, templates.leftRooms.Length);
Instantiate(templates.leftRooms[rand], transform.position, templates.leftRooms[rand].transform.rotation);
}
else if (openingDirection == 4)
{
rand = Random.Range(0, templates.rightRooms.Length);
Instantiate(templates.rightRooms[rand], transform.position, templates.rightRooms[rand].transform.rotation);
}
spawned = true;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("SpawnPoint"))
{
if(other.GetComponent<RoomSpawner>().spawned == false && spawned == false)
{
Instantiate(templates.closedRooms, transform.position, Quaternion.identity);
Destroy(gameObject);
}
spawned = true;
}
}
}