using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class StartupScript : MonoBehaviour
{
public TextMeshProUGUI startupText;
public bool gameHasStarted = false;
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
gameHasStarted = true;
}
if(gameHasStarted)
{
startupText.enabled = false;
}
}
}
I have this script in a scripts folder and, as a component of a canvas. When I open the inspector for this script in the scripts folder, it doesn't have the public bool checkbox for gameHasStated, and it won't allow me to set a TMPro instance to startupText. Neither of these problems occur when I open the inspector for the same script in the canvas.
When I run the game, and press space, it comes back with the error
NullReferenceException: Object reference not set to an instance of an object StartupScript.Update () (at Assets/Scripts/StartupScript.cs:21)
How do I fix this?
CodePudding user response:
After the I checked your code in Unity, I make the following points:
The code is working fine, neither compilation nor runtime.
I suspect that you tried to drag&drop TMPro instance from the hierarchy, which is not possible.
The explanation is that setting a default reference, in other words while you are selecting the script which is in the folder, you are editing data project and file wise. The hierarchy is the scene data, not the file data, that is why it is not possible. While the prefab is a file, therefore you can assign it.
I do not know why your program throws NullReferenceException, since in my test no such errors were produced. Double check that you assigned a valid reference.
CodePudding user response:
When I open the inspector for this script in the scripts folder, it doesn't have the public bool checkbox for gameHasStated, and it won't allow me to set a TMPro instance to startupText.
This is perfectly normal! Think of your script as more of a "blueprint" of the component that you'll place in your scene. Each instance of the blueprint is its own object, with its own gameHasStarted
and startupText
.
Neither of these problems occur when I open the inspector for the same script in the canvas.
This is precisely what you want. Assign the object references to the instance on your canvas.
Now, about the error.
The error indicates that the instance of your StartupScript
does not have the startupText
assigned. You can fix it by filling in that field:
If it says "None" it's highly likely that you forgot to assign it and your script will crash with an error (like it did).
Also, take note that you could, in theory, have multiple instances of the StartupScript
throwing you off -- one could be assigned while the other is throwing errors. If you suspect this, click on the error in the console and it should highlight the specific object that has the script on it that's throwing the error.