Any better way to do a 'switch' statement?

0 favourites
  • 7 posts
From the Asset Store
Toggles Dials Switches and Alerts ! A foundational sound grouping of Analog type switches and Steampunk effects
  • So, a situation such as below is quite common.

    E.g. simply choosing a block depending on the value of a variable. Doing it like that is kind of a bad/inelegant practice from logic perspective (because it always checks all the conditions and also doesn't make sure only one block is triggered), so is the only alternative doing a if-else pyramid of doom here?

    (and if so, will C3 ever get a switch statement?)

  • There is a SwitchCase addon for C2, but it's a bit awkward to use.

    If you have lots of conditions, it may be better for performance to add "Else" to all subsequent conditons. Also, you can use "StoppedOnBlock Is between values 7 and 11" in the last one.

  • Usually if you have a block of repetitive conditions like that, there's a better way to do it without the repetition. For example lots of conditions with an incrementing number could be replaced by a single read from an array. But it depends on exactly what you're doing, which isn't shown in your post.

  • You have no "or" in that last part, so that's a bit worrisome.

    A loop with stop loop?

    Then again we don't know what your circumstances are. This may not be the best method to get to the desired result.

  • dop2000

    Hmm I checked out the plugin but it seems a bit wonky from the comments. Will indeed go with the else statements I think. As to the last one, in fact all of these conditions should be separate; I took the screenshot mid-work and didn't notice they pasted all in one block.

    Ashley

    I agree about a single read from an array; in this case though they all need to run unrelated bits of their own logic with no common denominator to reduce to. Well maybe this is not that common a use case after all...

    newt

    As above the last one should be separate blocks; my bad for a sloppy screenshot. A cool idea about doing a loop with a 'stop loop' though - I'll toy around with it.

    Ok then, thank you for the answers - I'll try out some things.

    I'd still argue some sort of a switch functionality would come in useful.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • You didn't show what actions you need to perform in each case. It may be possible to optimize all these events if the actions are similar. Say, if you need to change some other variable based on StoppedOnBlock, you can use ternary operator:

    Set var to (StoppedOnBlock=1? "red": StoppedOnBlock=2? "blue": StoppedOnBlock=3? "green": .....)

  • I agree. A switch statement would come in handy for sure.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)