How to block a raycast? (Java)

Hi, Im trying to implement a shield system for my project, the idea is that if the shield is being held up then it’ll block any incoming attacks.

Now, when the enemy is in range it’ll use a Raycast function to see if the player is in range and send a notification to damage him, here’s the code that makes that work:

var hit : RaycastHit;
	if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit)) 
		Distance = hit.distance; 
		// Checks if the raycasted object is in the range of attack
		if (Distance < AttackRange) 
			// Calls the function "Apply Damage" on the object that's being hit
			hit.transform.SendMessage("ApplyDammage", attackDMG, SendMessageOptions.DontRequireReceiver);

What Im wondering is if there’s a way to effectively block this raycast if an object such as the shield is in the way.
I tried giving the shield a collision box to see if that would stop the damage notification from reaching the player but that didnt work.

Is there any way to make that work? I know that I can probably make a condition to stop the player from receiving damage when the shield is up but I still want him to get damaged if he’s hit on the back.

There are a number of ways of solving your problem. Which one to use will depend on your game:

  1. Turn off the collider on your player when the shields are up.

  2. Change the name or the tag on the player when the shields go up and check the name or tag in your raycast:

    if (hit.collider.tag == “Player” && Distance < AttachRange) {

  3. Use a child game object with a collider larger than your player. Enable the collider when the shields go up. Check the name or tag as in #3.

  4. Use GetComponent() to get the player script and check the shields variable directly:

    var player : PlayerScript = hit.collider.GetComponent(PlayerScript);
    if (player != null && !player.shieldsUp && Distance < AttachRange) {