r/gamemaker • u/Privatizitaet • 3d ago
Resolved Why is the else statement breaking this?
if (global.split == 2){
global.split = 1;
}
else {
global.split = 2;
}Essentially, I got two instances of an object, and I want to essentially swap control between them with a button press. I got a global variable for that and got spawn conditions to have a local variable different for each instance, probably not the most efficient way but I'm just getting started.
Now, when I *just* do the if statement it properly swaps to the other instance. However, I want to be able to swap back and forth, which I can't do with just that, so I added an else.
If the variable is 2, it's supposed to make it 1.
If the variable isn't 2, it's supposed to make it 2.
Pretty simple.
But for some reason the else breaks it. It just doesn't swap at all and I don't get why.
4
u/Majestic-Singer7503 3d ago
global.split = 3 - global.split;
1
u/No_Assistant_2554 3d ago
I assume this code is in the step event. It does not break it just follows the logic you are giving. You are essentially saying: if split is 2 make it 1, else (as in if split is not 2) make it 2. So if you variable is 1 the else statement kicks in and makes it 2. Basically ist circles through this constantly.
1
u/BobHobbsgoblin 2d ago
Make it so that when your key gets pressed it increases global split by one, put a line into your step event that if global split is greater than two then global split = global split minus 2.
That'll make it so that it's always only ever going to be one or two.
3
u/Melodic_Gold4862 3d ago
As a general rule I'd put your code inside of the step event using code checks for the key press as it makes it easier to manage and debug, I've always found other gamemaker events like Key Press to be frustrating for this kind of thing.
The alternative is to use a Switch statement to create a mini state machine as someone else said. These are a good thing to get used to using in general and are more robust than if/else checks.
0
u/sylvain-ch21 hobbyist :snoo_dealwithit: 3d ago
this code should be fine; do you reset the value of global.split to one in a step event or anything else somewhere?
also it is in the key press (would run everyframe which could be the reason it feels like it fails sometime) or the key pressed event (run once)
-1
u/nainainaii 3d ago
Tbh not sure why you’re having this issue, maybe a switch case would work?
Switch(global.split)
{
Case 1:
Global.split = 2
Break;
Case 2:
Global.split = 1
Break;
}