I am trying to set up a script for a rail shooter that uses raycasting for shooting instead of just cloning objects . everything worked except for when the raycast collides with the enemy it throws this error
NullReferenceException: Object reference not set to an instance of an object
Player.RaycastShoot () (at Assets/Player.cs:50)
Player.Update () (at Assets/Player.cs:65)
im trying to get it to run the function in a script on an enemy. or if there is an easier way to set it up to deduct health from the enemy on each hit i would greatly appreciate knowing.
public void RaycastShoot ()
{
Enemy enemyObj;
enemyObj = gameObject.GetComponent("Enemy") as Enemy;
Vector3 _ray = new Vector3(Input.mousePosition.x,Screen.height - Input.mousePosition.y - 100,0);
Ray ray = Camera.main.ScreenPointToRay(_ray);
RaycastHit hit;
if(shootTimer > 0)
shootTimer -= Time.deltaTime;
if(shootTimer <= 0)
shootTimer = 0;
if(shootTimer == 0)
{
if(Input.GetKey(KeyCode.Mouse0))
{
shootTimer = shootDelay;
if(Physics.Raycast(ray, out hit, 100f))
{
Debug.DrawRay(_ray, transform.TransformDirection(Vector3.forward), Color.green);
GameObject otherObj = hit.collider.gameObject;
// Part of the code that is throwing an error
if(otherObj.tag == "Enemy")
{
enemyObj.EnemyDmg(damage);
print ("Hit an Emeny");
}
}
}
}
this is the line that is causing the error
if(otherObj.tag == "Enemy")
{
enemyObj.EnemyDmg(damage);
print ("Hit an Emeny");
}