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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

OnTriggerEnter2D - is there any other way to specify triggered object?

Discussion in 'Scripting' started by ProExCurator, May 5, 2020.

  1. ProExCurator

    ProExCurator

    Joined:
    Jan 2, 2020
    Posts:
    87
    So far I was using tags to specify with which object there will be interaction, but I wonder if I can use for example SerializeField for that?

    The way I'm doing it so far:
    Code (CSharp):
    1.     void OnTriggerEnter2D(Collider2D collision)
    2.     {
    3.         if (collision.CompareTag("Trigger"))
    4.         {
    5.             trigger = collision.gameObject.GetComponent<TriggerScript>();
    6.             trigger.switcher = 1;
    7.             Destroy(gameObject);
    8.         }
    9.     }
    Is there any way to use something like SerializeField:
    Code (CSharp):
    1. [SerializeField]
    2.     private GameObject Trigger;
    ?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,204
    You could, but then you'd only care about interactions with a single gameobject:

    Code (csharp):
    1.  
    2.     void OnTriggerEnter2D(Collider2D collider)
    3.     {
    4.         if (collider.gameObject == Trigger)
    5.         {
    6.  
    Which might be what you want?

    You could also just check if the component you care about is there:

    Code (csharp):
    1.  
    2.     void OnTriggerEnter2D(Collider2D collider)
    3.     {
    4.         if (collider.TryGetComponent<TriggerScript>(out var trigger)) {
    5.             trigger.swticher = 1;
    6.             Destroy(gameObject);
    7.         }
    8.     }
    9.  
     
    ProExCurator likes this.
  3. ProExCurator

    ProExCurator

    Joined:
    Jan 2, 2020
    Posts:
    87
    This is exactly what I needed. Thank you!

    I wanted to avoid adding sooo much tags to my game.