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 MerlinsMaster · Mar 17, 2017 at 02:02 AM · variablestaticnull reference exception

NullReferenceException: Object reference not set to an instance of an object

Hey guys,

This one's really testing my sanity, so I'm hoping you can help. I'm getting a null error from one of my scripts when I call a variable from another script, and I can't figure out what the reason is.

Now I have a script called cs_GM that is attached to an empty called GameManager, which holds static references to several scripts in my game. I have another script called cs_UIManager which displays all of my UI, which is attached to the UI canvas. And the script I'm having the problem with, called cs_LivesDisplay, is also attached to the canvas that cs_UIManager is attached to. In it, it calls a variable called currentLives from a script called cs_LivesManager, which is attached to the GameManager object.

The problem I'm having is that when it calls that variable, it returns null, and I can't figure out why it's returning null. If I copy/paste the line that calls the variable to cs_UIManager, it works fine from there.

I'm sure I'm missing something simple. Can someone please point it out to me?

Here are the relevant scripts. Sorry to leave so many, but I don't want to leave out something that might be the problem. Thanks.

cs_GM

 using UnityEngine;
 using System.Collections;
 
 public class cs_GM : MonoBehaviour {
 
     public static GameObject Player;
 
     public static cs_PlayerMove ref_cs_PlayerMove;
     public static cs_PlayerDamage ref_cs_PlayerDamage;
     public static cs_PlayerInventory ref_cs_PlayerInventory;
     
     public static cs_SpawnManager ref_cs_SpawnManager;
     
     public static cs_UIManager ref_cs_UIManager;
     public static cs_ItemHUD ref_cs_ItemHUD;
 
     public static cs_TimeManager ref_cs_TimeManager;
 
     public static cs_ScoreManager ref_cs_ScoreManager;
 
     public static cs_PlayerRespawn ref_cs_PlayerRespawn;
 
     public static cs_CameraFollow2D ref_cs_CameraFollow2D;
 
     public static cs_LivesManager ref_cs_LivesManager;
 
     public static cs_ReachExit ref_cs_ReachExit;
 
     public static debugTest ref_debugTest;
 
 }

cs_UIManager

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class cs_UIManager : MonoBehaviour {
 
     public Text healthAmount;
     public Image healthBar;
     public Image timeBar;
     public Text enemiesAmount;
     public Text scoreAmount;
     public Text timeElapsedAmount;
     public Text timeLeftAmount;
     public Text livesAmount;
     public Text bombsAmount;
 
 
     void Start ()
     {
         cs_GM.ref_cs_UIManager = this;     // allows this static script to be accessed by the other scripts
 
         DisplayUI();
     }
     
     
     void Update ()
     {
         DisplayUI();
     }
 
     void DisplayUI()
     {
         healthAmount.text = cs_GM.ref_cs_PlayerDamage.playerHealth.ToString("0");
         healthBar.fillAmount = cs_GM.ref_cs_PlayerDamage.playerHealth * 0.01f;
         timeBar.fillAmount = cs_GM.ref_cs_TimeManager.timeLeft * 0.05f;
         bombsAmount.text = cs_GM.ref_cs_PlayerInventory.hasBomb.ToString("0");
         timeElapsedAmount.text = cs_GM.ref_cs_TimeManager.timeElapsed.ToString("000");
         timeLeftAmount.text = cs_GM.ref_cs_TimeManager.timeLeft.ToString("00");
         scoreAmount.text = cs_GM.ref_cs_ScoreManager.score.ToString("000");
         livesAmount.text = cs_GM.ref_cs_LivesManager.currentLives.ToString("0");
 
         Debug.Log(cs_GM.ref_cs_LivesManager.currentLives);  // **** DOES NOT RETURN NULL ****
 
     }
 }

cs_LivesDisplay, in which I am getting the error

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class cs_LivesDisplay : MonoBehaviour 
 {
 
     void Start () 
     {
         Debug.Log(cs_GM.ref_cs_LivesManager.currentLives);  // ****RETURNS NULL****
     }
     
 }


cs_LivesManager

 using UnityEngine;
 using System.Collections;
 
 public class cs_LivesManager : MonoBehaviour 
 {
     public int currentLives = 3;            // the number of lives the player has
 
     void Start ()
     {
         cs_GM.ref_cs_LivesManager = this;     // allows this static script to be accessed by the other scripts
     }
 
     void Update ()
     {
         if(currentLives == 0)           // if player has no more lives
         {
             Debug.Log("Game Over");     // call Game Over function here
         }
     }
 
     public void GiveLife()
     {
         currentLives++;  // increments lifeCounter by +1
         
     }
 
     public void TakeLife()
     {
         currentLives--;  // increments lifeCounter by -1
         
     }
 }
Comment
Add comment · Show 3
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 SnStarr · Mar 17, 2017 at 02:24 AM 0
Share

Did you make sure to drag the Lives Display Text Game object to the REFERENCE to it in the Inspector ON the Game $$anonymous$$anager Game Object?

avatar image MerlinsMaster SnStarr · Mar 17, 2017 at 02:42 AM 0
Share

I didn't have text for that. What I did have was an array of game objects of the UI image objects that I had on the screen. And then a For loop to set them as active or not active depending on how many lives the player had.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class cs_LivesDisplay : $$anonymous$$onoBehaviour 
 {
     public GameObject[] lifeGraphic;
 
     void Start () 
     {
         for (int i = 0; i < 6; i++)
         {
             if(cs_G$$anonymous$$.ref_cs_Lives$$anonymous$$anager.currentLives >= i)
             {
                 lifeGraphic[i].SetActive(true);
             }
             else
             {
                 lifeGraphic[i].SetActive(false);
             }
         }
     }

avatar image Ahsenhein · Mar 17, 2017 at 03:52 AM 0
Share

Just had this problem and I still can't figure it out because I think it's a bug becaue It was working normally(tested!). And after a couple of $$anonymous$$utes I come back to PC to come back to work and bag, null reference in some of my scripts and a scriptable object lost its reference too. I mean....wtf is that?

3 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by Commoble · Mar 17, 2017 at 03:00 AM

I think I see your problem. The Start events for each script component in the scene are called sequentially when the scene loads, and if the Start event in cs_LivesDisplay is called before the Start event in cs_LivesManager, then it'll try to access cs_GM.ref_cs_LivesManager before it's been initialized, giving you a null reference error.

There's a few ways to fix this:

1) You could have cs_LivesManager initialize cs_GM.ref_cs_LivesManager in the Awake event instead of Start. For objects that are part of the scene when the scene starts, Awake and Start are functionally identical, except all the Awake events are called first, so any code in an Awake event is guaranteed to run before any code in a Start event (excluding objects instantiated during runtime).

2) You can force scripts to execute in a specific order in Edit -> Project Settings -> Script Execution Order. The manual describes this feature as affecting Awake, OnEnable, and Update; I believe it affects Start too, but I'm not certain.

3) You can change all the fields in your game manager script from static fields to instance fields and link your scripts to them in the inspector instead of in Start events.

Comment
Add comment · Show 2 · 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 MerlinsMaster · Mar 17, 2017 at 03:44 AM 0
Share

That's what it was. Oh, man, thanks so much. I hadn't thought about that at all.

I may consider implementing your number 3 suggestion later on though. Are there any downsides to that method? Does is affect performance in any significant way?

avatar image Commoble MerlinsMaster · Mar 17, 2017 at 04:33 AM 0
Share

Performance shouldn't be any worse or better than using static fields.

avatar image
0

Answer by toddisarockstar · Mar 17, 2017 at 02:56 AM

NullReferenceException: Object reference not set to an instance of an object is a common error. it means that Somehwhere in you code you are trying to use a game object variable before it is assigned. to find where your error is check to see if your gameobject variables are "null" before you try to access its scrips or components.

 if (gameobjectvariable==null){print("this is where my problem is"):}

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 oigetinthevan · Nov 07, 2020 at 06:46 PM

This may not resolve your issue, but restarting Unity seemed to fix it for me.

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

68 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

Related Questions

Global Variables Refuse to Cooperate 1 Answer

Variable access simulateneously 3 Answers

I´ve got a problem with my Coin System. It always shows 1 Coin. 2 Answers

Specific enemy variable affects all enemies 2 Answers

Is there any way to edit variables inside other scripts without declaring them as static? 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