Space Shooter Score Text NullReference error
Hello all, I am using the most current version of Unity3d (5.4.1) and I am following the Space Shooter tutorial. I am at the point of adding points to the game when the player destroys the asteroids, part 3 section 2 "Counting points and ending the game". However, when all the code is written, and I go to test, when the player shoots, the bolts go through the asteroids, and asteroids go through the player. Collision must be happening because the explosions still happen when the bolt hits the asteroid, and when the asteroid hits the player. During testing I get the error "NullReferenceException: Object reference not set to an instance of an object" in my DestroyByContact script. I have identified the culprit code piece, however I am at a loss as to how to fix it. When I comment out the code piece in the DestroyByContact script 'gameController.Addscore(scoreValue)' everything works fine, except for adding the score.
Please let me know if you would like me to post my scripts. Much thanks in advance!
if you're looking for help then posting the complete error message and associated code (properly formatted) is essential to help us help you.
before doing that though, go back through the part of the tutorial and make sure that you followed EVERY step EXACTLY as shown - the tutorials are generally correct.
Same situation, not working... Can't drag Score Text also. Watched tutorial twice.
Answer by NinjaCoded · Sep 27, 2016 at 10:05 PM
@gjf thanks for the quick reply. i followed the tutorial step by step again just to be sure my code is in line. However i am still getting the same error and in game results. So first here is my error code
Severity Code Description Project File Line Suppression State
Error NullReferenceException: Object reference not set to an instance of an object Solution 'Space Shooter' (1 project) Assets/Scripts/DestroyByContact.cs 35
Here is the DestroyByContact code
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour
{
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private GameController gameController;
void start ()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
}
void OnTriggerEnter(Collider other){
if (other.tag == "Boundary")
{
return;
}
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag =="Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
}
//gameController.AddScore(scoreValue);
gameController.AddScore(scoreValue);
Destroy(other.gameObject);
Destroy(gameObject);
}
}
And here is my GameController script just in case
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour
{
public GameObject hazard;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public GUIText scoreText;
private int score;
void Start()
{
score = 0;
UpdateScore();
StartCoroutine(SpawnWaves ());
}
IEnumerator SpawnWaves()
{
while (true)
{
yield return new WaitForSeconds(startWait);
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
public void AddScore (int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
}
Any suggestions are greatly appreciated! sorry if my code isnt properly formatted, still new to this community and unity itself :p
Answer by OctoMan · Sep 27, 2016 at 10:58 PM
Do you have a GameController GameObject in your scene?
Do you have tagged it correctly?
Is the script GameController attached to it?
Is the GameController GameObject active?
Does the debug line fires at start?
Did you dragged in the text field into your GameController?
Edit: Your Score Text variable is wrong! Except you really use GUIText and not Text in the Canvas System. In the GameController make use of the namespace:
using UnityEngine.UI;
and instead of:
public GUIText scoreText;
use
public Text scoreText;
And test again.
@Octo$$anonymous$$an Thank you for helping me out. To your questions yes GameController GameObject is in the scene, tagged, script attached, and active, and the text field has been dragged into GameController. After making the above changes I am now getting two different errors. Here is the error
NullReferenceException: Object reference not set to an instance of an object
GameController.UpdateScore () (at Assets/Scripts/GameController.cs:50)
GameController.Start () (at Assets/Scripts/GameController.cs:21)
Here is my game controller script
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : $$anonymous$$onoBehaviour
{
public GameObject hazard;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text scoreText; //newline
public int score;
void Start()
{
score = 0;
UpdateScore ();
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()
{
while (true)
{
yield return new WaitForSeconds(startWait);
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
public void AddScore (int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
}
I noticed on the function UpdateScore () there is a space between Score and the () . Is this correct? I'm assu$$anonymous$$g it is because i checked the DoneGameController Script and it is the same there. Thanks a million. Despite it not being solved yet, the help means a lot. ty ty ty ty ty P.S. I am also no longer able to drag the Score Text game object into Game Controller Game Object. Thanks again.
Answer by AntikHauz · Feb 11, 2018 at 12:28 PM
You may also want to make the make a new function for game controller: see the codes below for "DestroyByContact":
public GameObject explotion;
private GameObject newProjectile;
public GameObject playerExplotion;
public int scorePoints;
void gameController_Main()
{
GameController gameController = new GameController();
gameController = GameObject.FindObjectOfType<GameController>();
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameController != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot Find 'GameController' script");
}
gameController.AddScore(scorePoints);
}
********************************************************************************************************************
//And declare it on void OnTriggerEnter(Collider other)
*********************************************************************************************************************
void OnTriggerEnter(Collider other)
{
if (other.tag == "Boundary")
{
return;
}
newProjectile = Instantiate (explotion, transform.position, transform.rotation) as GameObject;
if (other.tag == "Player")
{
newProjectile = Instantiate(playerExplotion, other.transform.position, other.transform.rotation) as GameObject;
}
gameController_Main(); //this the declaration of the function gameController_Main
Destroy(other.gameObject);
Destroy(gameObject);
}
********************************************************************
for the code in "GameController" make that:
**********************************************************************
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public GameObject hazard;
public Vector3 SpawnValue;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
private GUIText scoreText; //make the GUIText as private
private int score;
void Start ()
{
GameObject scoreTextObject = GameObject.FindWithTag("ScoreText");
if (scoreTextObject != null)
{
scoreText = scoreTextObject.GetComponent<GUIText>();
}
if (scoreText == null)
{
Debug.Log("Cannot Find 'scoreText' Script");
}
score = 0;
UpdateScore();
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (-SpawnValue.x, SpawnValue.x), 0.0f, SpawnValue.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
}
Hope this will help.