Search Unity

RaycastHit2D.collider always null?

Discussion in '2D' started by ccn01347, Sep 19, 2014.

  1. ccn01347

    ccn01347

    Joined:
    Sep 3, 2014
    Posts:
    1
    I have custom buttons created by sprites, which has component of BoxCollider2D. I want to Raycast for the detection of touch. following is what I set it up:

    There are 3 buttons in a Control_3, BtnLeft, BtnCenter and BtnRight, those setting:

    And following is the code what I did fot the detection of touch:

    1. void update(){
    2. int i =0;
    3. while(i <Input.touchCount){
    4. Touch t =Input.GetTouch(i);
    5. if(t.phase ==TouchPhase.Began){
    6. RaycastHit2D hit;
    7. hit =Physics2D.Raycast(Camera.main.ScreenToWorldPoint(t.position),Vector2.zero);
    8. Debug.Log(hit.collider);
    9. if(hit.collider !=null){
    10. Debug.Log(hit.collider.name);
    11. }
    12. }
    13. i++;
    14. }
    15. }
    However, the hit.collider always return a null value. I have no idea why would it happen. Could anyone help me, please?
     
  2. secondbreakfast

    secondbreakfast

    Joined:
    Jan 5, 2013
    Posts:
    98
    collider is the property for the 3d version so it will be null if you have a 2d collider on it. I think there is a collider2d property.
     
  3. NamekGames

    NamekGames

    Joined:
    May 13, 2014
    Posts:
    11
    This answer is completely incorrect. hit.collider returns a Collider2D in this case.