I’ve been working a locational damage mechanic for my FPS game and rather than use tags, I’m using enums instead.
The code I have right now works fine, but I’ve had difficulty converting it to a switch statements.
Below is the relevant parts of code:
public void rayShoot()
{
Vector3 rayFrom = fpsCam.ViewportToWorldPoint (new Vector3 (0.0f, 0.0f, 0.2f));
RaycastHit Hit;
Debug.DrawRay(rayFrom, fpsCam.transform.forward * magRange, Color.green);
if(Physics.Raycast (rayFrom, fpsCam.transform.forward, out Hit, magRange))
{
enemyLow enemyL = Hit.transform.GetComponentInParent<enemyLow>();
bColl enLimbs = Hit.collider.GetComponentInChildren<bColl>();
if(enemyL !=null)
{
if(enLimbs.currBody == Body.Head)
{
Debug.Log("Headshot");
enemyL.headshot();
}
else if(enLimbs.currBody == Body.lShoulder)
{
Debug.Log("Shoulder Left");
enemyL.hitThres = 1;
enemyL.locationDamage();
}
else if(enLimbs.currBody == Body.rShoulder)
{
Debug.Log("Shoulder Right");
enemyL.hitThres = -1;
enemyL.locationDamage();
}
else if(enLimbs.currBody == Body.lArm)
{
Debug.Log("Left Arm");
}
else if(enLimbs.currBody == Body.rArm)
{
Debug.Log("Right Arm");
}
else if(enLimbs.currBody == Body.lLeg)
{
Debug.Log("Left Leg");
}
else if(enLimbs.currBody == Body.rLeg)
{
Debug.Log("Right Leg");
}
else
{
Debug.Log("No specific part hit");
enemyL.TakeDamage();
}
}
However, when I try to change it to a switch statement to make the code a little cleaner like so:
enemyLow enemyL = Hit.transform.GetComponentInParent<enemyLow>();
bColl enLimbs = Hit.collider.GetComponentInChildren<bColl>();
if(enemyL !=null)
{
switch(enLimbs.currBody)
{
case enLimbs.currBody.Head:
Debug.Log("Headshot");
break;
default:
Debug.Log("No specific area shot, apply normal damage");
break;
}
Unity gives me an error of:
Assets\Naomi\Scripts\Weapon.cs(315,11): error CS0176: Member ‘Body.Head’ cannot be accessed with an instance reference; qualify it with a type name instead
Enum script code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Body {
Head,
Chest,
lShoulder,
rShoulder,
lArm,
rArm,
lLeg,
rLeg,
Hip
};
public class bColl : MonoBehaviour {
public Body currBody;
}
Is it possible to break it down into switch statement or am I just left with functional - but not neat - code for this game mechanic?