- Home /
Getting a " NullReferenceException: Object reference not set to an instance of an object " - Space Shooter Tutorial 14 - Counting Points
Hello everyone,
As many other users, I am a first timer to both Unity and Programming, so please be patient with any ignorant questions that may come from me.
The Problem
I keep getting an error that says "NullReferenceException: Object reference not set to an instance of an object" whenever I run the game.
It is causing the game to detect collision, but does not destroy the objects or update the score.
There is a particular line of code that is guilty of the error, but I cannot find a clear answer, even with my wonderful Google-fu fingers. The minute I comment-out this offending line, everything works fine.
Details:
I am following a tutorial for the Space Shooter, and have landed on Step 14 : Counting Points
I have gone over the tutorial 3 times, and for the life of me I cannot see what I am doing that is drastically different from the teacher.
Please keep in mind that some of the concepts taught in this tutorial were from an older version of Unity. I currently run 5.5.2f1
Essentially the script "DestroyByContact" code is attempting to grab a function from one game object (in this case from the game object and class GameController) and use it once an object is destroyed. I thought that I was referencing them accurately, but I guess I am wrong? (Or Unity has changed so drastically that this no longer applies?).
I removed pieces of the code that have nothing to do with the problem at hand for the "GameController" Script. Fyi.
HELP! c:
Debug Log
NullReferenceException: Object reference not set to an instance of an object
GameController.UpdateScore () (at Assets/Scripts/GameController.cs:81)
GameController.AddScore (Int32 scoreValue) (at Assets/Scripts/GameController.cs:76)
DestroyByContact.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/DestroyByContact.cs:40)
DestroyByContact Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyByContact : MonoBehaviour
{
public GameObject explosion; // Reference to grab a public gameObject for explosion- to then instantiate
public GameObject playerExplosion; // Reference to grab a public gameObject for a Player explosion- to then instantiate
public int scoreValue;
private GameController gameController; //GameController is the class name we are referencing to. "gameController" is what we named the variable.
private GameObject gameControllerObject;
void Start ()
{
gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent <GameController>();
}
if (gameController == null)
{
Debug.Log ("Cannot find 'GameController' script");
}
}
void OnTriggerEnter(Collider other) // A built in Unity method to handle collision triggers.
{
if (other.tag == "Boundary") // OnTriggerEnter, if tag is boundary, return
{
return; //hands back control to the method that called it. This way, "Boundary" is never destroyed, and is persistently being ignored.
}
Instantiate (explosion, transform.position, transform.rotation); // instatiates explosion OnTriggerEnter
if (other.tag == "Player") // if tag is player, instatiate
{
Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
}
gameController.AddScore (scoreValue);
Destroy (gameObject); // destroys the shot on contact
Destroy (other.gameObject); // destroys an object the laser collides with on contact
}
}
GameController Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
public GameObject hazard; // Public reference for a hazard GameObject, in this case the asteroid
public Vector3 spawnValues; // Vector3 to set the Spawn parameters of the hazard/enemies
public int hazardCount; // Public reference to set how many hazards you want per wave
public float spawnWait; // This variable sets how much time to wait before the next gameObject spawn
public float startWait; // This variable sets how much time before the first spawn starts
public float waveWait; // This variable sets how much time to wait before the next Wave of spawns
public Text scoreText;
private int score;
void Start()
{
StartCoroutine(SpawnWaves ());
score = 0;
UpdateScore ();
scoreText = GetComponent<Text> ();
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore ();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
}
Answer by ShadyProductions · Jun 02, 2017 at 05:50 PM
scoreText is null in:
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
Answer by SekraTezul · Dec 22, 2017 at 08:24 PM
While Shady is correct you may not know what that means. Much like creating your spawnwait and startwait sections you now have a Public Score Text area in your Game Controller Inspector when you have your Game Controller selected in your hierarchy in the unity program itself. The issue is not the script at all it is that you haven't shown the script where to put your text output. Drag your ScoreText from your Hierarchy into the Score text window of the Gamecontroller to show unity where to utilize the information coming from the script you just created.,While Shady is correct you may not know what that means. When it says that your Scoretext is a null-reference; It means that you have created a text location export on your Gamecontroller in Unity in the 'Inspector' portion when the Game controller is selected in your Hierarchy. It should be at the bottom of the Game Controller(Script) section where you need to drag your ScoreText from Hierarchy into this space so it knows where to output the text when executing the script.
Answer by krismarcovich73 · Mar 12, 2019 at 12:32 AM
how to fix this thanks... NullReferenceException: Object reference not set to an instance of an object PauseScript.Update () (at Assets/Scripts/PauseScript.cs:32)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement;
public class PauseScript : MonoBehaviour { GameObject PauseMenu; bool paused;
void Start()
{
paused = false;
PauseMenu = GameObject.Find("PauseMenu");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
paused = !paused;
}
if (paused)
{
PauseMenu.SetActive(true);
Time.timeScale = 0;
}
else if (!paused)
{
PauseMenu.SetActive(false);
Time.timeScale = 1;
}
}
public void Resume()
{
paused = false;
}
public void MainMenu()
{
SceneManager.LoadScene(3);
}
public void Save()
{
PlayerPrefs.SetInt("currentscenesave", SceneManager.GetActiveScene().buildIndex);
}
public void Load()
{
SceneManager.LoadScene(PlayerPrefs.GetInt("currentscenesave"));
}
public void Exit()
{
Application.Quit();
}
}
@krismarcovich73 $$anonymous$$ost likely, Pause$$anonymous$$enu
is null, meaning GameObject.Find
, surely because the object does not exist in the scene, or the object is not enabled at the beginning of the game. To fix:
public class PauseScript : $$anonymous$$onoBehaviour {
// Drag & drop the pause menu gameObject in the
// `Pause$$anonymous$$enu` field inside the inspector
public GameObject Pause$$anonymous$$enu;
bool paused;
void Start()
{
paused = false;
}
Your answer
Follow this Question
Related Questions
How to use OnTriggerEnter on different gameobject to detect collision? 3 Answers
Having trouble coding an on/off toggle for an animation in script. Please help! 1 Answer
How do I make do I make a variable go back to its original value for a spell system 1 Answer
store many GameObjects 2 Answers
Yellow problem on VSCode,working code but worried.Referencing another script variable. 1 Answer