Having a problem with Destroying a gameObject

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

Thanks! Changed all instances of "hit.gameObject" to "hit.collider.gameObject" and the problem was fixed.

1 Answer

1

Maybe this problem was fixed, but you will have another one when more than one enemy is around: when an enemy dies, all others die with him. That’s not solidarity: the health and alive variables were declared static, and static variables are common to all instances. In other words, there’s actually only one health variable for all enemies. You should remove the static keywords from the two variables in EnemyHealth.js, and access them like below:

         ...
         Debug.Log("You shot the " + hit.collider.name); // name is accessible via collider too
         // try to get the enemy script:
         var eHealth: EnemyHealth = hit.collider.GetComponent(EnemyHealth);
         if (eHealth) // if the enemy has such script...
         {
            eHealth.updateHealth(-10); // apply damage to it...
            if(!eHealth.alive) // and check if it's still alive:
            {
              Destroy(hit.collider.gameObject); // it's dead: go to hell, enemy!
            }
         }
         ...