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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

[NullReferenceException] Code works the way I want but still returns error

Discussion in 'Scripting' started by biggestboss, Aug 3, 2017.

  1. biggestboss

    biggestboss

    Joined:
    Aug 3, 2017
    Posts:
    3
    Hi, I'm trying to make an in-game log that actually runs the way I want it to but it returns an error in the console:

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. log.newActivity (System.String activity) (at Assets/scripts/log.cs:22)
    3. log.FixedUpdate () (at Assets/scripts/log.cs:32)
    Here is the code for the script I'm using:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. // http://answers.unity3d.com/questions/508268/i-want-to-create-an-in-game-log-which-will-print-a.html
    7.  
    8. public class log : MonoBehaviour {
    9.  
    10.     private int maxLines = 500;
    11.     private Queue<string> queue = new Queue<string>();
    12.  
    13.     public Text logText;
    14.  
    15.     // adds new line to in game log at the bottom and retains a certain number of lines, defined by int maxLines
    16.     public void newActivity(string activity) {
    17.         if (queue.Count >= maxLines) {
    18.             queue.Dequeue ();
    19.         }
    20.         queue.Enqueue(activity);
    21.  
    22.         logText.text = "";
    23.         foreach (string st in queue) {
    24.             logText.text = logText.text + "\n" + st;
    25.         }
    26.         Canvas.ForceUpdateCanvases ();
    27.     }
    28.  
    29.     // debug method to test log functionality
    30.     public void FixedUpdate() {
    31.         if (Input.GetKeyDown ("f")) {
    32.             newActivity ("An activity was added to the log.");
    33.         }
    34.     }
    35. }
    36.  
    Attached are screenshots of the inspector showing that I have assigned a Text to the Log Text field in the inspector and of what happens when I run the script in game.





    Thanks in advance for any help. If any more information is needed, I will provide it if I can.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    Do you have multiple log scripts in your scene? That's what it looks like to me.
     
    biggestboss likes this.
  3. biggestboss

    biggestboss

    Joined:
    Aug 3, 2017
    Posts:
    3
    I feel so stupid... That was exactly right. Thank you so much.