I'm trying to make a shooting game and I wanted to check if an enemy is hit using a raycast. Here is the code:
void CheckForShooting()
{
Vector3 mousePos = Input.mousePosition;
RaycastHit2D bulletCheck = Physics2D.Raycast(gunPoint.position,Camera.main.ScreenToWorldPoint(mousePos), gunRange);
Debug.DrawLine(gunPoint.position,Camera.main.ScreenToWorldPoint(mousePos),Color.white);
if(Input.GetButtonDown("Fire1"))
{
if (bulletCheck.collider.tag =="Enemy")
{
print("Hit");
}
}
}
However, even if the raycast is right on top the red enemy the console doesn't print "Hit" and I get the error "NullReferenceException: Object reference not set to an instance of an object", the line that is getting this error is this one bulletCheck.collider.tag =="Enemy"
.
Here is a ss:
Screenshot]
CodePudding user response:
You need to make a raycast everytime you click the Fire1
Look at this official unity site: https://learn.unity.com/tutorial/let-s-try-shooting-with-raycasts# its explained how to shoot with raycasts. I wish i could help you directly but i haven't entered Unity in over a year. I hope this helps but for such simple questions its faster to make a google search in my opinion
CodePudding user response:
You just need to check if collider you were supposed to hit is null or not (if it was actually hit). You shoot the ray and expect it to always hit the target in your current code. Just check:
if(bulletCheck.collider != null)
and the code will only run if there was a hit. Only then you can check what was hit. Also follow the advice and learn about NullReferenceException, it is the most common and basic exception, also one of the easiest to solve.