- Home /
NullReferenceException when using raycast
hey simply I'm trying to get an enemy to spot the player using ray casting. I'm getting the error "NullReferenceException: Object reference not set to an instance of an object" from this line of code
var rayDirection : Vector3 = player.transform.localPosition - transform.localPosition;
Here's the main chunk of code
var maxDistance : float;
var player : GameObject;
var rayDirection : Vector3 = player.transform.localPosition - transform.localPosition;
var enemyDirection : Vector3 = transform.TransformDirection(Vector3.forward);
var angleDot = Vector3.Dot(rayDirection, enemyDirection);
var playerInFront = angleDot > 0.0;
var playerClose = rayDirection.sqrMagnitude < maxDistanceSquared;
I admit I am not a out and out programmer but I do usually work things out eventually, has me particularly confused though. Its probably something really obvious hahah
thanks for the help.
Answer by CodeMasterMike · Jan 14, 2013 at 03:01 PM
Eihter player and/or transform is not set. If you can't tell from your code which one it may be, you can do a simple check to see which one that isnt valid:
if(player == null)
{
Debug.Log("player is null");
}
if(transform== null)
{
Debug.Log("transform is null");
}
Good luck!
Well that's really odd, because the error message says one of these variables are not set.
What do you get in the debug window, if you use these lines:
Debug.Log(player);
Debug.Log(transform);
thats just says
player (UnityEngine.GameObject) UnityEngine.Debug:Log(Object)
and
GameObject (UnityEngine.Transform) UnityEngine.Debug:Log(Object)
Well, that's a really strange problem you got there. You get a NullReferenceException error even though both objects are valid...
never$$anonymous$$d I solved the issue, well I didn't so much solve it as in I opened up Unity and it doesnt come up anymore, I don't know if was me being stupid or Unity haha thanks for your help anyway
Your answer
Follow this Question
Related Questions
Getting a Vector2 position depending on the rotation of an object 0 Answers
transform position and rotation of instantiated object 1 Answer
JS Dynamic Height Camera vibrating =( 1 Answer
C# Raycast goes straight into the air 2 Answers
How to make a gameobject rotation equal to ray transform? 0 Answers