- Home /
Question by
RandomUser123 · Aug 21, 2014 at 08:18 PM ·
raycastnullreferenceexceptionhit
Issue with raycast hit
I have this code in my Update function:
if(Input.GetButtonDown ("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
//Throws an error here
Debug.Log (hit.collider.gameObject.name);
if(Physics.Raycast(ray, out hit))
{
//Does not get here
Debug.Log ("here");
}
}
The error I get is:
NullReferenceException: Object reference not set to an instance of an object
raycast.Update ()
I don't really know what's causing it, this is all I have. Can anyone help out?
Comment
Wiki
Answer by Stefan Alexander · Aug 21, 2014 at 08:30 PM
Give this a go and let me know what happens:
var TheDamage : int = 50;
var Distance : float;
var MaxDistance : float = 1.5;
var TheSystem : Transform;
function Update ()
{
if (Input.GetButtonDown("Fire1"))
{
//Attack animation - IF YOU ARE GETTING ERRORS BECAUSE YOU HAVENT MADE AN ANIMATION AND ATTACHED IT, DELETE THE FOLOWING LINE.
animation.Play("Attack");
}
if (animation.isPlaying == false)
{
animation.CrossFade("Idle");
}
if (Input.GetKey (KeyCode.LeftShift))
{
animation.CrossFade("Sprint");
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
animation.CrossFade("Idle");
}
}
function AttackDamage ()
{
//Attack function
var hit : RaycastHit;
if (Physics.Raycast (TheSystem.transform.position, TheSystem.transform.TransformDirection(Vector3.forward), hit))
{
Distance = hit.distance;
if (Distance < MaxDistance)
{
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613161210im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Hit distance Change light range 1 Answer
How to hit two object with one raycast? 2 Answers
Need help with Third person shooter 0 Answers
Help Playing "Sound Clip" on RayCastHit? (RayCast help?) 2 Answers
RaycastHit.distance 1 Answer