- Home /
Object reference not set to an instance of an object
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");
}
Which specific line of that code is throwing the exception?
Seems like either otherObj or enemyObj is null. $$anonymous$$y guess would be enemyObj. The line towards the top where you set enemyObj: enemyObj = gameObject.GetComponent("Enemy") as Enemy;
Are you sure it's finding what you expect? Before the code that's causing the error, do something like: if (otherObj == null) print "otherObj is null"
if (enemyObj is null) print "enemyObj is null".
Once you find out which one is null, it's on to finding out why.
Answer by kmeboe · Oct 02, 2012 at 05:25 PM
Try changing your code to this:
// Part of the code that is throwing an error
if(otherObj.tag == "Enemy")
{
Enemy hitEnemyObj = otherObj as Enemy;
if (hitEnemyObj)
{
hitEnemyObj.EnemyDmg(damage);
print ("Hit anemony");
}
else Debug.LogError("Error: hit an object with tag \"Enemy\" that is not an Enemy!");
}
Your answer
Follow this Question
Related Questions
AI raycasting problem 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException when an object is in the way that is not the player 1 Answer
Picking Weapons Up with Raycast 1 Answer