- Home /
Use Enum in an if statement from a different script
I've looked for this answer in quite a few places on this forum, but so far none have proved helpful to get the job done. So my situation is, I have a "Boss" that is controlled by an enum in a script. He has 6 states (in the enum), one of them being Special. These are triggered in the Update() method with a switch statement inside of it. So when the CurrentState is BossActions.Special, it calls Special() in the switch statement which is going to move the boss and then i want him to shoot.
I created another script called BossSpecial where I want to check if the BossAction.Special == true and then call the method if so. Something like
void Update()
{
if(BossScript.BossActions.Special == true )
{
Shoot();
}
}
public void Shoot()
{
//code here
}
I know you can't do this this way but I don't know how to accurately compare it. I've tried setting it equal to a variable and then comparing that, but i couldn't figure that out. I tried taking the enum out of the class, but I don't think that's my answer either. I'm just not sure how to check in this instance.
Answer by Eno-Khaon · May 15, 2016 at 06:52 PM
You almost have it. Just make sure that you're calling on the right values.
You have the enumerator, then you have the value from that enumerator:
// BossScript
public enum BossActionsEnum { Special, Attack, Etc }
public BossActionsEnum bossActionsValue;
Then, when you go to use it:
if(bossScriptInstance.bossActionsValue == BossScript.BossActionsEnum.Special)
{
Shoot();
}
If you're calling them both from a different script (as per my example), you would use an instance of the script, along with its variable for the enumerator. Then, you would compare them with the root script's enumerator options to retrieve the value from it.
Namely, the instances:
bossScriptInstance.bossActionsValue
and the root script:
BossScript.BossActionsEnum
It never seems to grab the value of the enumeration though. Do I have to set them equal to each other at some point? I did the whole
public enum BossActions
{
Idle,
$$anonymous$$oving,
Chasing,
Patrolling,
Special,
}
public static BossActions bossActionsValue;
I declared it as static so I could reference it in the other script. and then in the if statement I had
If (BossScript.bossActionsValue == BossScript.BossActions.Special)
{
print("We're shooting);
Shoot();
}
But it never seems to fire off
bossActionsValue is a variable, so you do need to give it a value.
If the variable is static, that means you can only have a single state for your boss' activity. Specifically, this means that if you have multiple boss enemies simultaneously, they can only perform the same actions as each other, since they're sharing that global variable.