Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by thee0ry · Jun 02, 2017 at 05:51 PM · scripting beginnerscriptingbasicsreferencereferencingreference-other-object

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;
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by ShadyProductions · Jun 02, 2017 at 05:50 PM

scoreText is null in:

  void UpdateScore()
  {
      scoreText.text = "Score: " + score;
  }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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();
 }

}

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hellium · Mar 12, 2019 at 07:27 AM 0
Share

@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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges