Problem applying damage using raycast

Bit of a weird problem I’m having to do with applying damage to an Enemy cube.

This code doesn’t work:

public RaycastHit hit;

	void Shoot ()
{
	Physics.Raycast(Cam.position, Cam.forward, out hit, range);
	//Debug.DrawLine (transform.position, hit.point, Color.red, 5);
	if(hit.collider.gameObject.tag == "Enemy")	    
	{
		GameObject Enemy = hit.collider.gameObject;
		Enemy.SendMessage("applyDamage", bulletDamage, SendMessageOptions.DontRequireReceiver);
	}

}

However, this does:

public RaycastHit hit;

	void Shoot ()
{
	Physics.Raycast(Cam.position, Cam.forward, out hit, range);
		//Debug.DrawLine (transform.position, hit.point, Color.red, 5);
	if(hit.collider.gameObject.tag == "Enemy")
            Debug.Log("HIT A ZOMBIE");	    
	{
		
		GameObject Enemy = hit.collider.gameObject;
		Enemy.SendMessage("applyDamage", bulletDamage, SendMessageOptions.DontRequireReceiver);
	}

}

The only difference is the Debug.Log line.

Can anyone help me out? I’ve only been doing this for a week and this has me really confused haha.

1 Answer

1

public RaycastHit hit;

void Shoot ()
{
	Physics.Raycast(Cam.position, Cam.forward, out hit, range);
		//Debug.DrawLine (transform.position, hit.point, Color.red, 5);
	if(hit.collider.gameObject.tag == "Enemy")
	{
		Debug.Log("HIT A ZOMBIE"); // INSIDE PARENTHESIS
		GameObject Enemy = hit.collider.gameObject;
		Enemy.SendMessage("applyDamage", bulletDamage, SendMessageOptions.DontRequireReceiver);
	}
	
}

Also that is really not the way to raycast. This will break if the raycast doesn’t return a hit. Use raycast in a conditional :

public RaycastHit hit;	

void Shoot ()
{
	if ( Physics.Raycast(Cam.position, Cam.forward, out hit, range) )
    {
	    //Debug.DrawLine (transform.position, hit.point, Color.red, 5);
	    if(hit.collider.gameObject.tag == "Enemy")
	    {
		    Debug.Log("HIT A ZOMBIE"); // INSIDE PARENTHESIS
		    GameObject Enemy = hit.collider.gameObject;
		    Enemy.SendMessage("applyDamage", bulletDamage, SendMessageOptions.DontRequireReceiver);
	    }
	}
	
}

Sorry I've just realised how badly worded my question is. The script I say works takes health off my cube, the script I say doesn't work doesn't take health off my cube.