Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Efficient flagging system

Discussion in 'Scripting' started by arnoldhide, Nov 28, 2020.

  1. arnoldhide

    arnoldhide

    Joined:
    Jun 2, 2014
    Posts:
    9
    hi!

    currently, I'm building my first game with a "kind of" flag system.
    for example, if a player reaching a certain point, something will happen.

    right now, I'm using if-else. but I wonder if there's a better and more efficient way to do this?

    also, one more question, is nested if-else can affect performance so much?
     
  2. Stoicheia

    Stoicheia

    Joined:
    Jun 25, 2020
    Posts:
    27
    You should use events. https://learn.unity.com/tutorial/events-uh

    Basically, the idea is that when the player reaches that point, you can fire an event like
    Code (CSharp):
    1. Player.PointReached();
    Then on any object which needs to respond to the player, like a door opening, you can write something like
    Code (CSharp):
    1. Player.PointReached += Open();
    in your Door script.

    Also, nested if-else's don't really affect performance, but it is usually bad practice. If you have a bunch of if-else statements going on, you should replace it with polymorphism (move the behaviour to the class you're dealing with so you can do something like Item.Use() instead of if(item is Food)...else if(item is Weapon)... else if(item is Whatever)...).
     
    arnoldhide likes this.
  3. arnoldhide

    arnoldhide

    Joined:
    Jun 2, 2014
    Posts:
    9
    I've looked around at events, not really understand yet, but it looks pretty neat!
    thank you for your reply.