I’m having a problem destroying a gameObject in my game. I’m using 2 scripts, one attached to the player and one attached to the enemy.
Here is the EnemyHealth script:
static var health:int = 100;
static var alive:boolean = true;
static function updateHealth(amount:int)
{
if(alive)
{
health += amount;
if(health <= 0)
{
alive = false;
}
}
}
This is the script attached to the player:
var rayDistance:int = 100;
function Update ()
{
var direction:Vector3 = transform.TransformDirection(Vector3.forward);
var hit:RaycastHit;
if(Input.GetButton("Fire1"))
{
Debug.DrawRay(transform.position, direction * rayDistance, Color.red);
if(Physics.Raycast(transform.position, direction, hit, rayDistance))
{
Debug.Log("You shot the " + hit.collider.gameObject.name);
if(hit.gameObject.GetComponent("EnemyHealth"))
{
EnemyHealth.updateHealth(-10);
if(!EnemyHealth.alive)
{
Destroy(hit.gameObject);
}
}
}
}
if(Input.GetButtonDown("Fire2"))
{
Debug.Log("Should Be Zoomed");
}
if(Input.GetButtonUp("Fire2"))
{
Debug.Log("Should UnZoom");
}
}
I hope that’s clear enough. Basically, at line 16, it checks to see if the hit has the EnemyHealth component, and if it does, then it decrements the health by 10. Then it checks to see if the enemy is still alive. If not, then it destroys the enemy. The error I get is “MissingFieldException: Field ‘UnityEngine.RaycastHit.gameObject’ not found.”
How can I fix this error. Any help would be greatly appreciated.
Thanks.
"Destroy(hit.gameObject)" - there is no gameObject property for a RaycastHit http://unity3d.com/support/documentation/ScriptReference/RaycastHit.html
– anon94818156Thanks! Changed all instances of "hit.gameObject" to "hit.collider.gameObject" and the problem was fixed.
– anon80605749