Why does it break the script if I declare it in Awake()?

Hello, I’m really enjoying the course so far and I’ve got some problems with the first part of Realm Rush. any help is appreciated

Why does it break the script if i put it on the Awake() when I’m doing exactly like the course? I’ve attached it to the text object in my prefab,

it just plays out
NullReferenceException: Object reference not set to an instance of an object
CoordinateLabler.DisplayCoordinates () (at Assets/Scripts/CoordinateLabler.cs:33)
CoordinateLabler.Awake () (at Assets/Scripts/CoordinateLabler.cs:15)

When I remove it from awake it just works fine (except for when i go into play mode, then it does not retain the coordinates). it just makes me scratch my head. am I missing something obvious? From what I’ve read its because the object is NULL but why is it working in the lecture?

ok so now its just broken :smile:

It breaks because label is null. You have not set label to anything. coordinates is never null because you initialise it immediately (and because it’s a struct which can never be null), so this code never executes

if (coordinates == null)
{
    label = GetComponent<TextMeshPro>();
}

Just check if the label is null instead

if (label == null)
{
    label = GetComponent<TextMeshPro>();
}

Thanks for the reply :slight_smile: it would have taken me quite some time to realize my mistake, this worked. I sat and pulled out a few hairs yesterday. I wonder why it works in the lecture :thinking: is it an older version of Unity you think?

It works in the lecture because Gary sets the label in Awake(), which you didn’t do.

im fairly certain i did before i started to noodle around with the null statements but yeah it could just have been that something else was wrong in the editor when i had it there. but anyways, thanks for your time and help :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms