I'm currently developing a game in Unity and I ran into a small problem. I'm trying to access a variable that is located in another class because I need it in order to be able to spawn a gameobject ("clock") at random during a specified amount of time while an update method is running. However for some reason even if I change the variable to a static variable or create a new instance of the class in which the variable I'm trying to access is located. I keep on getting an error message stating:
NullReferenceException: Object reference not set to an instance of an object InteractControl.Update () (at Assets/Scripts/Scene 2 Scripts/InteractControl.cs:87)
This is part of the class that I'm trying to access showing how the variable in question ("public Transform[] spawnPoints") is declared:
public class BallSpawnerControl : MonoBehaviour
{
public Transform[] spawnPoints = new Transform[] { };
int randomSpawnPoint, Interact;
int index = 1;
public static bool spawnAllowed;
public static int TimerOn = 1;
ObjectPooler objectPooler;
public static int LevelTrans = 1;
public static bool HeartSpawn = false;
private int Hearts = 1;
// Use this for initialization
public void Start()
{
objectPooler = ObjectPooler.Instance;
spawnAllowed = true;
InvokeRepeating("SpawnAInteract", 0f, 1f);
}
This is part of the class that is trying to access the variable showing how the variable in question ("public Transform[] spawnPoints") is being accessed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractControl : MonoBehaviour, IPooledObject
{
private Rigidbody2D rb;
GameObject target;
Vector3 directionToTarget;
public static int LevelStart = 0;
Renderer m_Renderer;
public static float moveSpeed = 5f;
public static bool isSlowMotion = true;
public static float timeLeft = 5f;
ObjectPooler objectPooler = ObjectPooler.Instance;
int randomSpawnPosition;
float randomSpawnTime;
int Spawn = 1;
BallSpawnerControl Bc = new BallSpawnerControl();
void Update()
{
if (target != null)
{
if (ScoreScript.scoreValue > 10)
{
timeLeft -= Time.deltaTime;
if (timeLeft > 0)
{
directionToTarget = (target.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
directionToTarget.y * moveSpeed);
if (Spawn == 1)
{
randomSpawnTime = Random.Range(1, 5);
randomSpawnPosition = Random.Range(0, Bc.spawnPoints.Length);
Spawn++;
}
if (timeLeft > randomSpawnTime && Spawn <= 2)
{
objectPooler.SpawnFromPool("Clock", Bc.spawnPoints[randomSpawnPosition].position, Quaternion.identity);
}
}
if (timeLeft < 0)
{
GameObject[] gos = GameObject.FindGameObjectsWithTag("ColouredBall Highress");
foreach (GameObject go in gos)
{
go.SetActive(false);
}
BallSpawnerControl.HeartSpawn = true;
}
}
}
}
}
What normally should happen is that the clock will spawn randomly at position "Bc.spawnPoints[randomSpawnPosition].position" during the 5 first seconds that ScoreScript.scoreValue > 10 .