Why are both of theese approches not working properly?

Approach 1


Approach 2

This is the script with the functions:

For whatever reason, in both cases i get this common Error:
21121212

What i truly dont understand is that in the second approach card.OnHover() is called, however card.IdleState() is not, even tho they are in the same script and in the same if statement.

Can anyone tell me a way to programm this the right was and perhaps tell me why the Raycast cannot understand the else in the if statment?

All help is appreciated

Before anything, use code tags with the whole code of your scripts, don’t use pictures. Pictures aren’t easy to read/copy code from and if we don’t have the whole code of each class like in the last picture we may miss something that you think it is irrelevant.

On the first approach, you declare a card variable that never gets populated with anything so when you try to use it is always null.

On the second, you try to populate the card variable with the Hit.collider.GetComponent<InteractableCard>(). If the object hit by the ray has a component of type InteractableCard then the card variable will reference this component, if not the card variable will stay null.

Inside the if Raycast statement, the card.OnHover branch will try to execute when the Hit.Collider.tag== "Interactable" is true. I say, try, because if the card is null (see above) it will throw an exception. If it is false then the card.IdleState() will try to execute, again this will throw an exception if the card is null.

The cartdOnHover() is called because the if statement inside you if Raycast statement is true, the card.IdleState is not because it is false.

Some things to fix:

  1. Check the card variable after its assignment for null. If it is null don’t use it anywhere. If it is null but you don’t expect it to be, find out what about your assumptions is wrong. In this specific example, you assume that everything that your ray hits has an “InteractableCard” component and if it also has the “Interactable” tag it executes the OnHover else it executes the IdleState

  2. From the last picture you use the getcomponents constantly, cache them and use the cached versions in the methods.

Use the TryGetComponent and if false return or check if the card is null after the GetComponent and return, so you won’t get the null reference exception whenever you hit something that is not with a “InteractableCard” component.

1 Like