Hey, I have a 2D Unity project. I have a script (LeftClick) attached to a door, with just a bool that sets to true when you click on the door.
I also have a script (Message Text) attached to a Panel in the UI, where a message will appear to say the door’s locked.
I tried to access the Door script from the Panel script:
private LeftClick leftClickScript;
public bool message = false;
public TextMeshProUGUI messageText;
public GameObject messagePanel;
void Start()
{
// Get the script from the door
leftClickScript = GameObject.Find("Door").GetComponent<LeftClick>();
}
void Update()
{
// If the door was clicked,
/*if(leftClickScript.clicky == true && message == false)
{
message = true; // set bool
messagePanel.SetActive(true); // make message panel visible
messageText.text = "It's locked. I should head to town first."; // Set message
leftClickScript.clicky = false; // reset door bool
}*/
}
This wasn’t doing anything, and I’ve made sure that everything in the Inspector is as it should be. I then stuck Debug.Log("test"); in the Start function just to see if the script was actually running at all. The Debug didn’t appear in the Console.
So then I tried flipping it, and referenced the Message Text script in the LeftClick script. That didn’t seem to do anything either.
I also tried checking if the Message Text script was null, in the LeftClick script.
void Update()
{
if(messageTextScript == null)
{
Debug.Log("WE'RE NULL WHY ARE WE NULL HELLPPPPP");
}
}
Now, THAT appeared in the Console.
I’m frustrated, can you tell?
This should work, because this exact technique was used in one of Unity’s own lessons. How and why is this script null? What do I do to be able to reference other scripts this way?
In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.
“Stop playing ‘Where’s GameWaldo’ and drag it in already!”
GameObject.Find is highly unreliable. Guess what happens if you have two or more objects named „Door“. Which one you get is „random“.
Generally make sure you log all references you think you might have gotten, but may not. Also get in the habit of comparing object‘s GetInstanceID() because only that number is unique for each object. If you set the Inspector to Debug mode you also see those IDs of the GO and components.
Well, you know what’s null. So the question is, where do you assign a value to the messageTextScript variable? Either that code isn’t being executed, or the value you’re assigning is itself null. BTW I agree completely with @CodeSmile that GameObject.Find is something to avoid, although in your case I don’t think that’s the problem since your LeftClickScript is running.