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?
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);
}
}
}