AddComponent in switch statement not working

I’ve encountered a problem when using a switch statement which could be solved by using a seemingly identical if statement.

The following code works:

            if(state == StateEnum.CHARGED)
            {
                gameObject.AddComponent<ChargedState>();
            }

The following code doesn’t work:

        switch (state)
        {
            case StateEnum.CHARGED:
                gameObject.AddComponent<ChargedState>();
                break;
            default:
                break;
        }

Shouldn’t those two be identical?

EDIT: Reformatted to code insert

Those look identical to me. When you say that the switch statement doesn’t work, what does it do? Have you tried putting a breakpoint at the top of the code and stepping through with the debugger, to find out what lines it executes, and what the values of variables are at each moment? (If you’re not familiar with using the debugger, I highly recommend taking the time to learn how to use it. It’s a programmer’s best friend.)

Also, what is the larger context? Maybe some of the code around the conditional is affecting its behavior. (And please use the code tag for anything more than a few lines of code; it helps with readability. There’s a button for it labeled Insert… on the post editor, to the left of the floppy disk save button.)

1 Like

Yes indeed they were identical. The problem had to do with how the state machine had bugs which had the first state created always be destroyed immediately. So when I added if statement the code but that was because that created a second state of the same type which then worked.