- Home /
Raycasthit NullRException
Well, i'm trying to make a simple Collision Side detection with raycast based on this example
But i'm getting a NullReferenceException at this line:
normal = rcashit.transform.TransformDirection(normal);
Code:
if (col.gameObject.tag == "Player") {
Ray obray = new Ray(col.gameObject.transform.position, (col.gameObject.transform.position - transform.position).normalized);
RaycastHit rcashit;
Physics.Raycast(obray, out rcashit);
Vector3 normal = rcashit.normal;
normal = rcashit.transform.TransformDirection(normal);
if (normal == rcashit.transform.right) {
t += 1;
if (t >= 30) {
PlayerController p = target.GetComponent<PlayerController>();
p.health -= 1;
t = 0;
}
}
}
Can please someone help me? Thanks!
Answer by robertbu · Feb 18, 2014 at 02:33 AM
You have to check the return value of Physics.Raycast() to see if the Raycast() hits anything. If the ray does not hit, then 'rcashit.transform' will be null. Something like. Alternately you could check to make sure 'rcashit.transform' is not null. But either way you do it, you need to make sure the Physics.Raycast() is hitting a game object.
if (Physics.Raycast(obray, out rcashit)) {
Vector3 normal = rcashit.normal;
normal = rcashit.transform.TransformDirection(normal);
if (normal == rcashit.transform.right) {
t += 1;
if (t >= 30) {
PlayerController p = target.GetComponent<PlayerController>();
p.health -= 1;
t = 0;
}
}
}
Your answer
Follow this Question
Related Questions
Calling 'AddItem' Method giving me error NullReferenceException: 0 Answers
RaycastHit2D.collider is null - why? 1 Answer
RacastHit object not set to an instance of an object 1 Answer
Why am I getting NullReferenceException on my .Contains()? 1 Answer
Select Object and move on Right click Position - Error! 0 Answers