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.

Is there a way to code triggers to react differently based on character options?

Discussion in 'Getting Started' started by aleenmax, Nov 24, 2022.

  1. aleenmax


    Nov 24, 2022
    My goal is to code triggers that affect only certain characters. Water characters will evaporate (die) if they are in fire or lava, and fire characters will extinguish (die) in water.

    For each element, I intended to create different triggers, so they would affect other characters differently. I don't know how to code triggers that respond differently to each character, despite having a plan. My experience with C++ and Java is limited, but I am learning how to use C# and Unity for the first time.

    For every water/fire character, I intend to set a public variable to a different char/int value, and if the public variable == [insert appropriate value], then the character will die. Having just copied the trigger code from Unity's Sample 2D platformer, I have no idea how to format or code it.

    Do you have any tips/guides/sample code you could share with me?
  2. Freakish


    Jun 3, 2015
    There are a number of ways to do what you wish.

    I use Switch Statements based on tags. So you would set a tag in Unity Inspector for example, one for Fire and one for Water as an example, and then use a Switch Statement which is checked when the trigger is hit.

    Hope it helps.

    Code (CSharp):
    1.   private void OnTriggerEnter(Collider other)
    2.     {
    3.         switch (other.tag)
    4.         {
    5.          case ("Water"):
    6.           //Do Water Stuff Here            
    7.            break;
    9.             case ("Fire"):
    10.             //Do Fire Stuff Here                
    11.             break;
    12.         }
    13.     }