Search Unity

OnTriggerEnter2D doubt.

Discussion in '2D' started by Deleted User, Sep 9, 2017.

  1. Deleted User

    Deleted User

    Guest

    Hi, I'm trying understand how this function works, my issue is:
    I need to call this function on another class that is declared. Example:

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2. public bool test=true;
    3. void Update() {
    4. if(test)
    5. Itemtrigger.OnTriggerEnter2D();
    6.  
    7.  
    8. }
    9. }
    ... and "OnTriggerEnter2D" is declared in another class, like :
    Code (CSharp):
    1. public class Itemtrigger : MonoBehaviour {
    2.  
    3. public static void OnTriggerEnter2D (Collider2D other) {
    4.  
    5.     }
    6. }
    When I tried to compile this, MonoDevelop gave me a error ("There is no argument given that corresponds to the required formal parameter 'other' of 'Itemtrigger.OnTriggerEnter2D(Collider2D)").

    What is the right arguments to call this ?
     
  2. sadsasddas

    sadsasddas

    Joined:
    Jun 17, 2017
    Posts:
    2
    Hi.
    I thinkk That i can help you.
    Under text you have a code. Checking "your tag" is optional, but if you delete this every tirigger Will be return 'obj enter in trigger'


    Code (CSharp):
    1.  void OnTriggerEnter2D(Collider2D col) {  
    2. if(col.collider.tag=="yourtag") { test=true;}
    3. }
    4.  
    5. void Update() {
    6. if(test) print("obj enter in tirigger);
    7. }
     
    Last edited: Sep 9, 2017
  3. Suzuka91

    Suzuka91

    Joined:
    May 7, 2014
    Posts:
    39
    OnTriggerEnter2D is a function that is called every time a collider enters on a gameobject's 2D collider marked as trigger.
    The propper way to use OnTriggerEnter2D is:
    Code (CSharp):
    1. public class ExampleClass : MonoBehaviour{
    2. void OnTriggerEnter2D(Collider2D other)
    3. {
    4. Debug.Log("hi");
    5. }
    6. }
    in a gameobject which has attached a 2D collider marked as trigger.


    And by the way, you should remove the static keyword, cause it makes no sense (it would be as a "shared method" for all Itemtrigger instances, so everytime a collider enters on a certain object, the rest Itemtrigger's objects would execute OnTriggerEnter2D(), even if there aren't any colliders entering on its colliders. Obviously is not a desirable behaviour)