Home > Blockchain >  How to reverse an If Statement when conditions are no longer met
How to reverse an If Statement when conditions are no longer met

Time:04-07

In my Unity project, I have an if statement set-up where if the conditions are true, my character's box collider will shrink to a specific value when crouching (along with movement speed change, turning speed, etc). And when my character is not crouching anymore, the box collider (along with the other parameters I mentioned) will return to its original size in the else statement.

However, I don't want to keep track of every parameter I change/need to reverse across all my scripts. In the future, my character's base parameters may change, which'll cause me to have to go back and change every else statement I ever make involving changing my character to its default parameters. I can create variables to store my base parameters so I wouldn't have to worry about copy-pasting values if I change them in Unity. But it'll eventually snowball into spaghetti-code territory if I do this method for every parameter I create/change in my scripts.

Is there a simpler way to code in C# where if an If statement is no longer true, it'll reverse all changes it made?

Psuedo code:

float height = 10.42f;
float movementSpeed = 95.89f;
if (condition1==true && condition2==true){
  height = 3.5f;
  movementSpeed = 40.125f;
}
*code to reverse all changes the If Statement made when it stops being true*

CodePudding user response:

Is there a simpler way to code in C# where if an If statement is no longer true, it'll reverse all changes it made?

No. If you want to revert to an earlier state you need to save that state in advance, e.g. in variables as you propose in the question.

CodePudding user response:

It's look like buff system , it can be todo and undo player status , And it's expandability , So you can design a buffsystem to do it like this:

public interface IBuff
{
    void Do(Player player);
    void UnDo(Player player);
}

public BuffAddHeight : IBuff
{
    public Do(Player player)
    {
        player.Height  = 100;
    }

    public UnDo(Player player)
    {
        player.Height -= 100;
    }
}

public BuffSeed : IBuff
{
    public Do(Player player)
    {
        player.speed  = 100;
    }

    public UnDo(Player player)
    {
        player.speed -= 100;
    }
}

public class Player
{
    // by the way , you can design a buff container to manager your buff.
    public void AddBuff(IBuff buff) { buff.Do(this); }
    public void RemoveBuff(IBuff buff) { buff.UnDo(this); }
}
  • Related