Search Unity

One Trigger script on multiple different named Trigger objects

Discussion in 'Scripting' started by wuannetraam, Jun 25, 2021.

  1. wuannetraam

    wuannetraam

    Joined:
    Oct 29, 2019
    Posts:
    87
    Example:
    I have a scene with 4 cubes with trigger enabled in the collider.
    The names are:
    Cube1
    Cube2
    Cube3
    Cube4

    I have a player object with the tag "Player".

    Now I can create 4 trigger scripts and assign them to the cubes.
    I don't think that this is the most efficient way. Is it possible to create 1 TriggerScript and detect on which object this script is assigned? Something like "if name is Cube1 and collider object is Player then do X" "if name is Cube2 and collider object is Player then do Y" etc...
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    358
    The simplest way would be creating one generic Trigger class, then creating the enum with values like "First", "Second", "Third" etc;
    Code (CSharp):
    1.  
    2. public MyEnum inspectorVariable;
    3.  
    4. public enum MyEnum
    5. {
    6.     First,
    7.     Second,
    8.     Third
    9. }
    10.  
    11. if (inspectorVariable == MyEnum.First && collidedWithPlayer)
    12.     Do();