fbpx

 

3rd person shooter ...
 

3rd person shooter shoot script error, I am lost. Null Reference Exception error.  

   RSS

0

after the shoot script cleanup section I am getting an error on line 27, the Ray rayOrigin ... line. it states that object reference not set to an instance of an object.

would anyone be able to point out what is the problem?

void Shoot()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 center = new Vector3(0.5f, 0.5f, 0);
Ray rayOrigin = Camera.main.ViewportPointToRay(center); (this line is giving me an NullReferenceException error)

RaycastHit hitInfo;

if (Physics.Raycast(rayOrigin, out hitInfo))
{
Debug.Log("Hit: " + hitInfo.collider.name);
Health health = hitInfo.collider.GetComponent<Health>();
if (health != null)
{
health.Damage(50);
}
}
}
}

Thanks for your help.

@earth2jeremy

hello @earth2jeremy sorry that you are having issues as we all sometimes do. about the only thing different that you have there is the " Health health = hitInfo.collider.GetComponent();
if (health != null)" and "health.Damage(50);" and the rest matches what i have ``` public void Fire()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 center = new Vector3(0.5f, 0.5f, 0);
Ray rayOrigin = Camera.main.ViewportPointToRay(center);
RaycastHit hitInfo;

if (Physics.Raycast(rayOrigin, out hitInfo))
{
Debug.Log("Hit: " + hitInfo.collider);
}
}
}``` and i assume that the health is defined on the enemy's script and defined there as well?

@earth2jeremy

Looking at this, and the line you are having issue with.. make sure you have a Camera set to main.. as that may be throwing your null here

Topic Tags
1 Answer
0

ah yes indeed, it was a camera problem thank you. 

Share:

 

 

Scroll to Top

Please Login or Register