This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Recently I've been creating a game, and I've been creating a Menu.
At the beginning the player opens the Menu and enters a name into a UI Text Field, which I will convert to a string, so the player may be called that name throughout the storyline.
I've come across another Script on this website:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GUIFieldTest : MonoBehaviour {
public GameObject playerName;
public void Start ()
{
var input = gameObject.GetComponent<InputField>();
var se = new InputField.SubmitEvent();
se.AddListener(SubmitName);
input.onEndEdit.AddListener(SubmitName);
//or simply use the line below,
//input.onEndEdit = se; // This also works
}
private void SubmitName(string arg0)
{
Debug.Log(arg0);
}
}
I have tweaked this code so I can include a prefab of the Text Field as a GameObject, however I have recieved an error saying:
NullReferenceException: Object reference not set to an instance of an
object GUIFieldTest.Start () (at Assets/Scripts/GUIFieldTest.cs:13)
I understand that this error means that there is nothing assigned, and I understand how to fix the NullReferenceException. I am able to run the game, however the game freezes and the text field is not clickable. You cannot enter any text.
I know this is a very simple question, but it would be great for an explanation.
var input = gameObject.GetComponent<InputField>() should be
var input = playerName.GetComponent<InputField>().
When you use gameObject.GetComponent, it will only find components on the GameObject the script is attached to.
I assume that your InputField GameOBject is the playerName variable.
If this is not true the do var input = GameObject.Find("YourInputFieldGameOBject").GetComponent<InputField>().
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
Hi im having a problem with this i tried for 2 Days now but i don't know how to fix it. Im a beginner in C# and hope you can help me.
Im trying to use a variable from another script but the console keeps sending me an error:
NullReferenceException: Object reference not set to an instance of an object
PlayerCombat.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scrips/PlayerCombat.cs:52)
public int attackDmg = 2; //Diffrent Script
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Enemy")
{
PlayerTakeDamage(currentPlayerHp, GetComponent<Enemy>().attackDmg);
}
}
static void PlayerTakeDamage(int currentPlayerHp, int attackDmg)
{
currentPlayerHp -= attackDmg;
if (currentPlayerHp <= 0)
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
The
GetComponent<Enemy>()
is on another object, you can call it if you
1
Create a public variable and add the enemy object
public GameObject enemy;
And then after you dragged your enemy inside it in the inspector you can:
enemy.GetComponent<Enemy>()
Without problems
2
The second thing you can do is just declaring the enemy object
GameObject enemy;
And in the Start() you can
enemy = GameObject.FindGameObjectWithTag("Enemy");
But for this, you need to add a tag in the inspector for the enemy.
After this you can access the enemy as before.
I've got a problem with creating coin counter for a game.
Underneath is a part of my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Jump : MonoBehaviour
{
private Text coins_text;
void Start()
{
coins_text = GetComponent<Text>();
}
the problem seems to be in the Update method:
void Update()
{
coins_text.text = coins.ToString();
}
Here is the error:
NullReferenceException: Object reference not set to an instance of an object
Any help is appreciated.
Jump.Update () (at Assets/Scenes/Jump.cs:34)
Welcome new user,
don't bother using "GetComponent",
instead use
public Text coins_text;
and open your editor and literally drag the "text item" in to that slot
(If you're not familiar with how to do that, check some basic tutes on Unity!)
Next,
if you do use "GetComponent"
add this line of code
if (coins_text == null) { Debug.Log("there's a f'up"); }
coins_text.text = coins.ToString();
it will clearly tell you if the Text item is actually missing!
NEVER EVER set the text in Update. You can't do that.
You should only set it when the integer value of "coins" changes.
There are many ways to do that, but just do it simply. Have a separate function you call, to change the display, when you need to.
I am new to C# and Unity and am having trouble finding a clear answer to my problem.
I am trying to create a simple TextMeshProUGUI text log buffer in a panel. The buffer itself works fine until I try to access it from another class - I believe because I am not creating the reference to the panel correctly.
Here is my code for the TextMeshProUGUI object collector:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class TextLogControl : MonoBehaviour
{
public TextMeshProUGUI textPrefab; // Unity prefab
public List<TextMeshProUGUI> textItems = new List<TextMeshProUGUI>();
[SerializeField]
public int maxItems = 100;
public void LogText(string newTextString, Color newColor)
{
Instantiate(textPrefab, transform);
textPrefab.text = newTextString;
if (textItems.Count >= maxItems)
{
textItems.RemoveAt(0); // I should probably be destroying something, but that's another question
}
textPrefab.gameObject.SetActive(true);
textItems.Add(textPrefab);
}
// The above function works correctly if I write a test function within this same class
}
Here is the code for the class that is trying to access the LogText() function:
using System;
using UnityEngine;
public class World : MonoBehaviour
{
Color defaultColor = Color.black;
public TextLogControl textLog;
public void Init()
{
// I need to create a reference here somewhere, but nothing I am trying is working
textLog.LogText("Welcome - you made it!", defaultColor);
}
}
I am putting the TextLogControl script on the Unity GameObject that is holding the TMP objects, and that works on its own.
I thought that I was creating a reference to the holder GameObject by dragging it onto my World object in Unity as below, but I am still getting an NRE when I call World.Init(), which means that I'm doing something wrong, but I cannot figure out what.
I thought this would create the reference that is not being created
Edit: The error I'm receiving is
NullReferenceException: Object reference not set to an instance of an object
When trying to run World.Init() - specifically, textLog is null, even though I have got it dragged onto the appropriate spot in Unity (I believe).
As this is so long for comment,
A null reference means that it is trying to access something that doesn't exist. You either forgot to drag something in the editor, or you are a step ahead and have something un-commented that should still be commented. Your code is using something that isn't there. I recommend you to add this piece of code to your files to check either the error is coming from NullRefrence of class or the else code.
TextMeshProUGUIs = textPrefab.GetComponent<TextMeshProUGUI>();
if (TextMeshProUGUIs == null)
{
Debug.LogError("No TextMeshProUGUI component found.");
}
I have created a simple 2d card game in Unity , While the user is playing the game , certain information is getting captured like (score,tries,time), When the user wins or loses the game then the appropriate scene (game over or Win scene) is getting triggered, in these 2 scenes id like to copy the info from the score, tries, time fields of the game to the appropriate labels of gameOver or Win, But it seems I'm doing something wrong..
I tried to find similar questions on StackOverflow, Youtube, the web; I checked the documentation and I tried different approaches.
Here is the code I'm working with at the moment, which seems totally correct to me, I don't get any errors, just nothings appears in the labels.
'''
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class win_results : MonoBehaviour
{
// public options script;
public Text score_final_text;
public Text tries_final_text;
public Text time_final_text;
public void player_win_results()
{
// script = a.getComponent<options>();
if (options.user_lvl_choice=="easy")
{
GameObject tries_final = GameObject.Find("tries_text_lvl1"); //finds the object named score_results
tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
GameObject time_final = GameObject.Find("TimeCounter_lvl1"); //finds the object named score_results
time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
GameObject score_final = GameObject.Find("score_lvl1"); //finds the object named score_results
score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
}
else if (options.user_lvl_choice == "hard")
{
GameObject tries_final = GameObject.Find("tries_text_lvl2"); //finds the object named score_results
tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
GameObject time_final = GameObject.Find("TimeCounter_lvl2"); //finds the object named score_results
time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
GameObject score_final = GameObject.Find("score_lvl2"); //finds the object named score_results
score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
}
}
As the code above shows I'm using GameObject.Find as the documentation states, I have double checked the names and typos, the scripts are correctly attached, I get no errors in the output, just nothing happens.
As you can see above I have added an extra "a" character at the end for debugging purposes, the "a" character also doesn't appear in the output, meaning that the gameObject find doesn't work correctly in my example.
What am I doing wrong?
Thanks in advance.
When you load a scene without the second parameter
SceneManager.LoadScene("scene2");
The old scene will be destroyed, all the GameObjects in that scene will also be destroyed except you've called DontDestroyOnLoad on it.
So if you haven't done this job yet, what you get in the new scene are empty data. You can print the values to check.
The easiest way to pass data through scenes is use static field. Create a class and add some static fields:
class Global
{
public static string user_lvl_choice;
public static string tries_final;
....
}
Then you can set or get these values from any scene.
Global.user_lvl_choice = "easy"
print(Global.user_lvl_choice);
Read more:
static
SceneManager.LoadScene
Object.DontDestroyOnLoad
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I keep getting this error on a score counter script for a game that I am makingthe score counter works but this error is just annoying and I dont want ot publish it with the errors stacking up.
Error:
NullReferenceException: Object reference not set to an instance of an object
ScoreCounter.Update () (at Assets/ScoreCounter.cs:26)
Script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreCounter : MonoBehaviour
{
public static int score; // The player's score.
public Text text; // Reference to the Text component.
void Start ()
{
// Set up the reference.
//text = GetComponent <Text> ();
// Reset the score.
score = 0;
}
void Update ()
{
// Set the displayed text to be the word "Score" followed by the score value.
text.text = "Score:" + score;
}
}
From the error message it's very clear that your text object is never instantiated.
I don't know enough about your use-case to recommend where it should be instantiated, but inside of Start() looks like a good place.
Cheers