Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

NullReferenceException error

Discussion in 'Scripting' started by UnityProdS, Feb 4, 2015.

  1. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    I am aware help for this error has been posted many times here and have received good responses too. Sorry for raising it again.

    Despite trying all options and studying various answers in the forum I am unable to resolve this issue. I am using Unity version 4.6.2 and working with JavaScript.

    In my experience Unity does throw up this error despite the gameobjects are attached to the scripts in the inspector. And sometimes removing the gameobjects and reattaching has helped me, though not always.

    I have created a Canvas element on stage and created a UI text element under Canvas, below is the script I am using

    var scoreText:UI.Text;
    function Awake()
    {
    scoreText=GetComponent(UI.Text);
    Debug.LogError("Debug log "+scoreText);
    scoreText.text="0";

    }


    UI text element is attached to the scoreText variable in the inspector, the Debug log does reflect a game object which means the variable is declared and referenced correctly however at the next line

    scoreText.text="0";

    It throws up the "NullReferenceException: Object reference not set to an instance of an object" error.

    further I have a custom function as below:

    function updateScore()
    {
    myScores++;
    scoreText.text="Score: "+myScores;
    print("scoreText.text "+scoreText.text);
    }


    here the line *"scoreText.text="Score: "+myScores;"* doesn't throw up the error.

    I find this very strange. Not sure where I am going wrong.

    Highly appreciate any help.
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Welcome to the forum!

    If you select the error message in your console, the game object in the hierarchy which was responsible for the error will automatically be highlighted. This allows you to inspect the game object to see whether everything is set up correctly.

    If you post code, please use code tags from now on:
    http://forum.unity3d.com/threads/using-code-tags-properly.143875/
     
  3. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Thanks for the response. Yes I confirm I have adequately ensured that the Text element is attached to the gameobjects script in the inspector. And as I mentioned another call made in a different function in the same script is not throwing up the error.

    And thanks for the pointer on how to include code. I will follow it moving forward.
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    If you have the script attached to more than one game object accidentally, the Awake function will always be called in all those game objects, while your updateScore will only be called where you want it.

    That means if you select the error message, you may find the game object to which the script was accidentally assigned.
     
  5. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Sure here it is, I made one small change I moved the initial declarations (Lines 23,24 and 25 as below) under Awake() to Start(). As it was impacting some other logic in the code.

    Thank you for the help.

    Code (JavaScript):
    1. #pragma strict
    2. import UnityEngine.UI;
    3. var distance_meter:int;
    4. //var speed:int;
    5. var mousePosition:Vector3;
    6. var moveSpeed:float = 0.05f;
    7. var mouseB:int;
    8. public static var myScores:int;
    9. var scoreText:UI.Text;
    10. public static var mainSpeed:float;
    11. var Spawners:GameObject;
    12. var SpawnerScript:Spawner;
    13. function Awake()
    14. {
    15.  
    16. }
    17. function Start ()
    18. {
    19.     distance_meter=0;
    20.     mouseB=0;
    21.     myScores=0;
    22.     SpawnerScript=Spawners.GetComponent(Spawner);
    23.     scoreText=GetComponent(UI.Text);
    24.     Debug.LogError("Debug log "+scoreText);
    25.     scoreText.text="0";
    26. }
    27. function getSpeed()
    28. {
    29.     return mainSpeed;
    30. }
    31. function FixedUpdate ()
    32. {
    33.     if(!Spawner.paused)
    34.     {
    35.           distance_meter++;
    36.         mousePosition = Input.mousePosition;
    37.         mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    38.         transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
    39.         if(transform.position.y>1.5)
    40.         {
    41.              transform.position.y=1.5;
    42.         }
    43.     }
    44. }
    45. function updateScore()
    46. {
    47.     myScores++;
    48.     scoreText.text="Score: "+myScores;
    49.     print("scoreText.text "+scoreText.text);
    50. }
     
  6. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    I have edited my post, could you please check the previous post again. I am almost sure this should resolve the issue.
     
  7. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Ok.

    Let me give you more background.

    I have a game object which is the main object in the scene, I navigate this object using the mouse position. This object has a script to which is attached the Text element. Now I have also created a prefab of this object so that other prefabs in the game can access this game objects properties. I did this as I realised that in Unity a gameobject in scene cannot access, edit properties of other game objects which are prefabs.

    Hence i have 2 instances (one in the scene) and the other as a prefab. This could be an issue based on what you are advising.

    As you can see I am a bit confused on how Unity treats gameobjects placed in the scene against the same gameobjects prefab. How it impacts the properties and methods of both and how can I update the properties through the script.
     
  8. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Quick question:
    When you select the message with the null reference exception, which game object is selected in the hierarchy?
     
  9. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    The prefab instance of the gameobject which I have clicked and dragged on the stage.
     
  10. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    I will try to test your script.

    Just another remark. You should use Update instead of FixedUpdate, because FixedUpdate is supposed to be used for physics only.
     
  11. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Could you make a screenshot where you have the error message selected, just like the game object which threw it, such that the inspector is also visible?
     
  12. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Sure here is the screenshot. I hope this helps.

    upload_2015-2-4_19-20-46.png
     
  13. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Could you make another screenshot where you have Angry_Dolphin_Pre selected, such that the Inspector content becomes visible.
     
  14. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    ok. here it is.
    upload_2015-2-4_19-37-57.png
     
  15. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    This line
    Code (csharp):
    1. scoreText=GetComponent(UI.Text);
    means that you set scoreText should be the component in the current game object of type UI.Text. Angry_Dolphin_Pre doesn't have a UI.Text component. That means scoreText becomes null. Any call like
    Code (csharp):
    1. scoreText.text="0";
    can not be executed because scoreText is null.

    I can see in the inspector that you dragged a UI.Text component into the scoreText slot. That means scoreText is not empty if you hit play, but as soon as the GetComponent call takes place, it will become null. The simple solution in your case is to remove the GetComponent line.
     
  16. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    OK let me understand this a bit and come back. Thanks again for all the help.
     
  17. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    After commenting the call to GetComponent the error is no longer there.

    so this means if I am attaching an element to a gameobject in the inspector I need not use Getcomponent. Am I right?

    Moreover I also see that the scoreText variable is not updated in real time when I score points, however when I stop the game play I can see the scoreText variable updated with the correct score.

    for example when I start Play the scoreText variable is "Score: 0" which is expected. If I score say 8 points, then the variable still shows "Score: 0" however when I stop the game play I see the variable suddenly updated to "Score: 8".

    Is this issue related to the one you helped me resolve? Thanks!
     
  18. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Yes. If the field in the inspector is empty or if you don't see the field in the inspector at all, GetComponent can be used to fill those fields.

    This doesn't seem to be related.
    You are updating the score in the function names updateScore. If you want the score to be updated, you need to call this function. Most likely you are not calling this function.
    When you stop the player, the score will automatically use the text that you entered in the Unity editor. If you e.g. set it to "I like chicken", it will always display that when you stop the player.
     
  19. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    In fact the scoreText variable does update, the updateScore function is called too (I am printing some values inside it to debug) . I can see the scoreText variable getting updated in realtime when I view it in the inspector however it is not displayed on the screen in realtime.
     
  20. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    I am calling the updateScore function when another game object collides with this game Object. The function is called and scoreText is updated when I view it in the inspector however not updated on the screen in realtime.

    If I call updateScore in Update function (to debug) the scoreText gets updated on the screen in realtime.
     
  21. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    I moved the
    Code (JavaScript):
    1.     scoreText.text="Score: "+myScores;
    in Update function and only updated the score in updateScore function.

    That seems to have done the trick. As the score is now updating in realtime too on the screen.

    Thank you so much for the kind help.
     
  22. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Good to hear you solved it on your own.
     
  23. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Thank you. I have one final question though.

    We can drag a prefab gameobject into the variable component of another prefab in the inspector however cant drag a non prefab (on the scene) gameobject into the variable component of a prefab in the inspector and vice-versa. Is this understanding correct? And if it is yes, why is it so? this will help me understand how to make better use of prefabs.

    thanks again for your guidance.
     
  24. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  25. UnityProdS

    UnityProdS

    Joined:
    Jan 11, 2014
    Posts:
    35
    Ok. Thank you for all the help.