#NullRefeferenceException Error

237 messages ยท Page 1 of 1 (latest)

shy bridge
#

line 19

vivid sundial
#

line 19 is
var selectionTransform = hit.transform;, yes?

shy bridge
#

oh ya i forget discord doesnt show tghe lines

#

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

vivid sundial
#

that is line 19?

vivid sundial
#

to me, it seems that Camera.main is undefined

#

this is surprising, but you may have multiple cameras in the scene, which could cause that to freak out

#

it is probably better to directly define a camera variable, and reference that instead

vivid sundial
little hearth
#

Is the camera attached to the Player object, because i don't even see a camera object?
And if it is, make sure it has the "MainCamera" tag

#

Actually, i don't see the lines for the viewport of the camera at all anywhere.... is it so simple you've deleted the camera? ๐Ÿ˜„

shy bridge
#

what i didnt deletethe camera

little hearth
#

Well, it's not in your hierarchy, unless you have it as a child of your Player object

vivid sundial
#

the MainCamera tag, that is

little hearth
#

NullExceptionError troubleshoot for me always ends up being one of these two:

  1. Does the object exist?
    Yes? Move to two
    No? Add it
  2. Is the reference to the object correct?
    Yes? (usually never if it's Yes on previous)
    No, fix the reference so it catches the object correctly.
shy bridge
#

opk ill try that

vivid sundial
#

could you just use a serialized reference, like I originally suggested?

#

it is probably better anyways, as then you don't have to rely on a single camera

little hearth
#

I mean... i have a vague feeling he doesn't even have the camera there at all, since i can't see it in the hierarchy, and i don't see the viewport lines coming from the character so i get a feeling it's not attached to the player, wich is the only not-expanded object in the hierarchy

vivid sundial
#

the camera is a child of Player, I guarantee it

little hearth
#

So... the object in the scene is not the player then i assume?

vivid sundial
#

which object in the scene, exactly?

little hearth
#

Ah i guess the ball is "Sphere"

#

The player is nowhere close to where he's looking in the scene.

#

I thought it was a capsule, wich most people use as "Player" early on lol

shy bridge
#

heres the video

#

#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We will start with basic FPS movement, inventory building, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival open-world...

โ–ถ Play video
little hearth
#

But i'd probably still make a proper reference in the code for the camera. Either by tag "MainCamera" or by child of player, or just by a public field reference it in the inspector

#

Make sure i can always see the reference properly.

#

@shy bridge Is your Camera a child of your Player Gameobject? And does it have the MainCamera tag?

shy bridge
#

ill look

vivid sundial
#

do you understand what a NullReferenceException is? it may help you understand what we're instructing you to do

little hearth
#

So, like this i assume?

little hearth
#

TL;DR a NullReferenceException is when your script can't find a GameObject you're telling it to use, so there reference of it is null

#

aka empty

shy bridge
#

oh

#

so its not picking up a object

vivid sundial
#

kinda?

little hearth
#

@vivid sundial It'd be the "nub" explanation

#

There's more to it

#

Like, i don't even know the full extent of things like that either ๐Ÿคทโ€โ™‚๏ธ

#

But i feel like it's general rule of thumb that either your code can't find the object reference, or the object actually doesn't exist

vivid sundial
#

not necessarily a GameObject, just any non-primative type

little hearth
#

Well, true

#

Can be anything that is null when it shouldn't be, basically. ๐Ÿคทโ€โ™‚๏ธ

#

@shy bridge Did you say you didn't have the MainCamera tag, and you do now?
Did that help?

vivid sundial
#

ok, good

shy bridge
#

i still get the error tho

little hearth
#

Solid

#

Oh

vivid sundial
#

oh

#

how did it help then?

little hearth
#

I think he just said yes to the tag question

shy bridge
#

one c\sec

#

now im getting this error

#

interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();

#

null

vivid sundial
#

yeah, ok, that's because not every object that the ray collides with has a InteractableObject component

#

you have to filter the results somehow

vivid sundial
#

you could do this in a few ways

  1. Guard the target code with a null check
  2. Tag your objects, and then guard with a tag check
  3. Put all of your interactables on a separate layer, and use a layer mask on the raycast
little hearth
#

I just checked in the guide, it's wrapped in an if statement so unless i'm being dumb atm, it shouldn't toss an error

shy bridge
#

damn i stil get it

little hearth
#

This is the awesome but also horrible thing about tutorials. if you follow every step exactly, it works. If you miss a tiny step somewhere, it becomes real annoying to find it, especially in the beginning of your game-dev experience before you've started getting used to what tosses errors

vivid sundial
#

ok, then interaction_text must be undefined

little hearth
#

I'm wondering... if it's issues with the reference to interaction_text

vivid sundial
#

also, why is this tutorial using snake case for c#?

#

that is quite dubious.

little hearth
#

What's snake case

#

I've never heard that before lol

vivid sundial
#

variables_written_like_this

little hearth
#

Oh

#

Some people like it

#

Some people live and die on that hill lmfao

#

ALWAYS UNDERSCORE EVERYTHING

vivid sundial
#

yes, however languages have standards

#

people not willing to put down their preferences for those standards are... questionable...

little hearth
#

Truuueee, but technically this is user-specific.

#

You can name a variable asdfnizsdnfuisduifg if you prefer that

#

or 1896525

vivid sundial
#

no, you can't name a variable 1896525

little hearth
#

Probably not, but you know what i mean

#

You've quite some freedom to name variables like you want

#

Some bastard i saw who did a movement script, used "num" "num1" "num2" etc up to num5, in a whole movement script.... i figured out in the end that num and num1 was X and Y direction of mouse ๐Ÿคฆโ€โ™‚๏ธ

#

@shy bridge Can you show/tell what you're doing when the error is tossed, and paste the whole script?

vivid sundial
#

ok, I'm really starting to question this tutorial...

#

wrong naming conventions, using GetComponent in Start()

#

bro's probably going to use a Find method in a sec here

little hearth
#

I think you're going to hate my scripts

#

lmfao

vivid sundial
#

oh, and using public, not [SerailizeField]

little hearth
#

hides

#

I've actually used both. But in my defense, atm, i'm just throwing something together that sorta works, before i start refining it.

vivid sundial
little hearth
#

@vivid sundial ๐Ÿคทโ€โ™‚๏ธ I've gone around most my scripts and set most to private and started referencing a lot by script rather than in the inspector. But i still have a bunch of publics left.

#

But i'm definitely doing GetComponents in my Start() methods a lot

#

Is one example.... hides

vivid sundial
#

nooooooooooo

little hearth
#

IT WORKS

shy bridge
shy bridge
vivid sundial
# little hearth

no, bro, you're using a find method... that's the real issue here

little hearth
#

@shy bridge Sorry i was talking to Wormy about that. BUT. In your case.....

#

Wheres the text component in the hierarchy?

#

on the Canvas?

vivid sundial
# shy bridge

*proceeds to show the player component and not the component in question*

little hearth
#

@vivid sundial Is it just me that find the text referencing a bit strange in the script?

vivid sundial
#

as I've told you, I believe the issue to be a missed reference to interaction_Info_UI

#

so I wanted to see if that was defined in the inspector

shy bridge
vivid sundial
#

the inspector...

#

that's the heirarchy

little hearth
#

You've a text object somewhere in your hierarchy. The Text interaction_text; variable that you're trying to reference via interaction_text = interaction_Info_UI.GetComponent<Text>();

#

but there's neither private or public before Text interaction_text; wich irks me a bit, but idk if it's doable that way.

vivid sundial
little hearth
#

What mark is that

vivid sundial
#

so, like `code here`

little hearth
#

OH

#

Cool.

shy bridge
#

oh i feel dumb

#

the interaction_info_UI was the text

little hearth
#

Soooo... you figured it out and it works now? ๐Ÿ˜„

little hearth
#

@vivid sundial Btw, since you didn't like my Find method... what'd you do? I know that some people out there tend to be "Never use Find by tag!" for example, but... it works

vivid sundial
#

[]find

#

ugh, the brackey's bot has changed

little hearth
#

@shy bridge Okay so... there's an issue with the reference.
The gameobject you have the script attached to, show the inspector. Aka this part:

#

@vivid sundial ngl, i use a lot of Find by tag.... because it works for me cross-scene and i use a lot of instantiated prefabs hmmge

shy bridge
cursive perchBOT
#

Don't use Find methods!

Find methods in Unity are an often-tempting solution to referencing a scene object. However, there is always a better solution.
Whenever you call a Find method, Unity must traverse your entire scene hierarchy and check every single object until it finds a match; and the methods which return arrays will always traverse the entire hierarchy regardless.
This is inefficient! It means that the more objects you add to your scene, the slower these methods become; and it gets even worse if you are calling them multiple times.

A non-exhaustive list of Find methods to avoid:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html

To read about a better solution, type []getareference or []getref

little hearth
#

@shy bridge interaction_info_UI is not a text component?

vivid sundial
shy bridge
little hearth
#

@vivid sundial Alright... i'll keep it in mind and work that in later. For now, i won't touch it since i got other things to do.

#

AHA

vivid sundial
little hearth
#

You're using TextMeshPro! There's your issue!

#

Problem found

shy bridge
little hearth
#

So! In your code, do this:

#

When you reference your text

#

(do not write private if you reference in the inxpector, without adding [SerializeField] on the line above)

#

So you'd like to do, in your case:

[SerializeField]
private TextMeshProUGUI interaction_text;
vivid sundial
#

it is clearly outdated (Text has been deprecated for quite some time now), and it is using very, very poor conventions, all around

shy bridge
#

im kinda new to the coding

little hearth
#

I've been in the same seat and gone through the same struggles.

#

I'm going to guess you're using the guide because you want to make a survival game? @shy bridge

vivid sundial
shy bridge
#

but what do i do for this? interaction_text = interaction_Info_UI.GetComponent<Text>();

vivid sundial
# shy bridge like a medieval type

instead of using tutorials that tell you how to make a particular game, you should try to find one that helps you with a specific problem

shy bridge
little hearth
#

@shy bridge Yeah, figured. I wouldn't want to tell you to stop per se, but a survival game is a huge undertaking and there's a lot of systems that interact with each other.
When you're new to coding, i'd (from experience) try and narrow the scope and make smaller things, to start to get used to programming.

But, if you're insistent on making a survival game. Take it step by step instead of get a tutorial for a whole "game".
Start with say Playermovement.
Then one for something else simple.
Then a new guide for some other part. Step by step etc.

#

@shy bridge replace Text with TextMeshProUGUI i believe is all you need to do

#

Wormy is going to pull his hair now, but i do the same thing here essentially:

little hearth
#

With that extra if statement, i also get an error in the log if the reference for the component is not found for whatever reason.

shy bridge
#

thanks for the help

#

also one thing

vivid sundial
little hearth
#

@shy bridge Get used to making null-checks like that if statement in my picture, so you can track your missing references easily.

shy bridge
little hearth
#

@vivid sundial I too, am an amateur and i don't know all the ins and outs. This works and the reason it is currently like this, is because i need to hard reference to a child of a prefab i instantiate into the scene.

#

It's ugly.... but it works

#

That's all i care about for the time being!

#

@shy bridge You mean the jump the first time you hover over the object?

shy bridge
#

ya

little hearth
#

That's a good question... Hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

vivid sundial
#

we would need to see the code for your camera controller to answer that question

little hearth
#

I wonder....

shy bridge
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;

public Transform orientation;

float xRotation;
float yRotation;

private void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

private void Update()
{
    // get mouse input
    float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
    float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

    yRotation += mouseX;

    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    // rotate cam and orientation
    transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
    orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}

}

#

one out of Dave/ GameDev

little hearth
#

I don't think the issue is there. Because it happens first when he hovers at the object

vivid sundial
#

[]cb

cursive perchBOT
#

Use codeblocks to send code in a message!

To make a codeblock, surround your code with ``` (3 backticks. Click here to see where the key is)

To use syntax highlighting, add the file extension of the language you wish to highlight (cs for C#, cpp for C++)

For example:
```cs
Console.WriteLine("Hello World");
```

Produces:

Console.WriteLine("Hello World");

To send lengthy code, paste it into https://paste.myst.rs/ and send the link of the paste into chat.

little hearth
#

So, it happens upon the raycast hitting the object

shy bridge
#
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        var selectionTransform = hit.transform;

        if (selectionTransform.GetComponent<InteractableObject>())
        {
            interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
            interaction_Info_UI.SetActive(true);
        }
        else
        {
            interaction_Info_UI.SetActive(false);
        }
    }
#

under this

vivid sundial
#

`, not '

shy bridge
#

thanks

little hearth
#

Perfect

vivid sundial
#

is there any other input here, or does this just happen when you hover?

#

no click or anything, right?

little hearth
#

But yeah, it's a bit strange it makes your camera jump, because your raycast doesn't affect your camera... ๐Ÿค” Even more strange was that when it also jumped, it didn't trigger showing the UI, but it did the next time

little hearth
#

Did you include the

else
{
interaction_Info_UI.SetActive(false);
}
little hearth
#

Oh yeah i'm blind

#

But then there's an issue there too, it doesn't clear the raycast

#

Because the label stays when he looks off of it

shy bridge
#

so its has to be the raycast system in my SelectionManager

little hearth
#

There's certainly something wonky with the raycast, but there might be something with the camera, or some other script that interacts with one or the other.

#

It's really hard to tell without being hands on with the project

shy bridge
#

true

little hearth
#

In this case, i say play around with it and see if you can figure it out.

#

The more you play around with, break, repair, scratch your head, cry, leave the PC, take a shit, come back, cry a bit more, smash it with a hammer.... the more you learn!

little hearth
#

I spent 10-12 hours on an issue the other night.

#

I discussed the issue with someone in another discord and he just managed to shine some light on some areas i need to check

#

And the next day i woke up, went to PC, checked it, and i figured it out!

vivid sundial
#

ok @shy bridge
I've looked through all the stuff you've shown thus far, and I have no idea what could be causing this

little hearth
#

Yeah i'm unsure aswell, bit of a headscratcher honestly. Hence i said just... mess around with it. There's not that much to your project yet that can cause issues.

#

Messing around is afterall the best way to learn ๐Ÿคทโ€โ™‚๏ธ

vivid sundial
#

to start debugging this, I'd print the values of xRotation and yRotation and see if they change when the camera jumps

#

if they don't, it may be something to do with the player parent, not the camera

little hearth
#

That's a good call

vivid sundial
#

if they do change, something is probably messing with the input axis

#

also, you should really use the new input system, it's way better!

#

again, something this tutorial doesn't cover, but it should

little hearth
#

Never show Wormy my code again HmmNoted

#

Joke aside, thanks for clarifying the thing about Find earlier pepo_hype @vivid sundial

vivid sundial
little hearth
#

@vivid sundial One thing at a time lol. I'll figure it out eventually. Now i at least know about it.