How to avoid duplicating if statement

In case you need to check the tag repeatedly in your code here is a way to avoid writing the same if statement over and over. This way, if you do need to change the “Breakable” string at least it is only in one place.

    private void OnCollisionEnter2D(Collision2D collision)
    {
        PerformActionOnBreakableBlock(() => DestroyBlock());
    }

    private void CountBreakableBlocks()
    {
        PerformActionOnBreakableBlock(() => level.IncrementBlocks());
    }

    private void PerformActionOnBreakableBlock(Action action)
    {
        if (tag == "Breakable")
        {
            action();
        }
    }
2 Likes

Privacy & Terms