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 /
  • Help Room /
avatar image
0
Question by NinjaCoded · Sep 27, 2016 at 10:38 AM · scripting problemerrornullreferenceexception

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!

Comment
Add comment · Show 2
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 gjf · Sep 26, 2016 at 07:23 PM 0
Share

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.

avatar image artrayd · Apr 18, 2017 at 02:35 PM 0
Share

Same situation, not working... Can't drag Score Text also. Watched tutorial twice.

3 Replies

· Add your reply
  • Sort: 
avatar image
0

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

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 OctoMan · Sep 27, 2016 at 10:58 PM

  1. Do you have a GameController GameObject in your scene?

  2. Do you have tagged it correctly?

  3. Is the script GameController attached to it?

  4. Is the GameController GameObject active?

  5. Does the debug line fires at start?

  6. 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.

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 NinjaCoded · Sep 29, 2016 at 08:15 AM 0
Share

@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.

avatar image
0

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.

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

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

100 People are following this question.

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

Related Questions

Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers

Bugs on my C# Scripts? 0 Answers

NullRefrenceException: Object refrence not set to an instance of an object. 0 Answers

Can someone help me fix this script up? 2 Answers

Setting button intractability causes an error 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