Search Unity

How to Make Detection of the Tag of a Trigger?

Discussion in '2D' started by FGPArthurVII, Jul 16, 2016.

  1. FGPArthurVII

    FGPArthurVII

    Joined:
    Jan 5, 2015
    Posts:
    106
    I needed to to detect what the tag of the trigger that the player is passing over, but the way I am doing the program presents me this error:

    Script error: OnTriggerStay2D
    This message parameter has to be of type: Collider2D
    The message will be ignored.

    Even if I try to run anyway, the force is not added, so the If inside OnTriggerStay2D doesn't work. It only work if I remove the tag checking after the && on the GetKey If on the OnTriggerStay2D void. Does someone know another way to detect what the tag of a trigger is and use it in a conditional?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Player : MonoBehaviour
    5. {
    6.     public Rigidbody2D rBody;
    7.     public Vector2 speed;
    8.     public Vector2 jumpStrength;
    9.     private Animator anim;
    10.     private bool isJumping;
    11.     public Vector2 antigrav;
    12.  
    13.     void Start ()
    14.     {
    15.         rBody = GetComponent<Rigidbody2D>();
    16.         anim = GetComponent<Animator>();
    17.     }
    18.    
    19.     void FixedUpdate ()
    20.     {
    21.         anim.SetBool ("isWalking", false);
    22.         if (Input.GetKey(KeyCode.RightArrow))
    23.         {
    24.             anim.SetBool("isWalking", true);
    25.             rBody.MovePosition(rBody.position + speed * Time.fixedDeltaTime);
    26.         }
    27.         if (Input.GetKey(KeyCode.LeftArrow))
    28.         {
    29.             rBody.MovePosition(rBody.position - speed * Time.fixedDeltaTime);
    30.             anim.SetBool("isWalking", true);
    31.         }
    32.         if (Input.GetKey(KeyCode.UpArrow) && !isJumping)
    33.         {
    34.             rBody.AddForce(jumpStrength);
    35.             isJumping = true;
    36.         }
    37.     }
    38.     void OnCollisionEnter2D(Collision2D coll)
    39.     {
    40.         if (coll.gameObject.tag == "Floor")
    41.         {
    42.             isJumping = false;
    43.         }
    44.     }
    45.     void OnTriggerStay2D(Collision2D collision2D)
    46.     {
    47.         if (Input.GetKey (KeyCode.LeftArrow) && collision2D.gameObject.tag == "AntigravityL")
    48.         {
    49.             rBody.AddForce (antigrav);
    50.         }
    51.     }
    52.  
    53. }
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    The error message tells you what the problem is; OnTriggerStay2D doesn't take a Collision2D as a parameter, it need to be a Collider2D. Just change it to the proper parameter type and things should work.
     
  3. FGPArthurVII

    FGPArthurVII

    Joined:
    Jan 5, 2015
    Posts:
    106