Search Unity

  1. We've closed the job boards. If you're looking for work, or looking to hire check out Unity Connect. You can see more information here.
    Dismiss Notice
  2. Unity 2017.3 has arrived! Read about it here.
    Dismiss Notice
  3. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

detect gameobject at position

Discussion in '2D' started by murado, Jan 12, 2018.

  1. murado

    murado

    Joined:
    Jan 24, 2016
    Posts:
    6
    before instantiating a prefab at a position i want to find out if there is already one in that area. i am using this method, but it doesnt work. The prefab that is instatiated has a 2d box collider and it has "is trigger".

    float xpos = Random.Range(5, -5);
    float ypos = Random.Range(5, -5);

    Collider[] hitColliders = Physics.OverlapSphere(new Vector2(xpos, ypos), 5);
    if (hitColliders.Length == 1)
    {
    Debug.Log("found something at that position");
    }
    else
    {
    Instantiate(powerup1, new Vector2(xpos, ypos), transform.rotation);
    }
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    5,115
    Code (csharp):
    1. if (hitColliders.Length > 0)
    Without a mask, the OverlapSphere will return any colliders so you probably want to use a LayerMask and the other override method for OverlapSphere.
     
  3. jeffreyschoch

    jeffreyschoch

    Joined:
    Jan 21, 2015
    Posts:
    2,144
    Is this a 2D game with 2D colliders? If so, you need to use Physics2D.OverlapCircle, to receive a Collider2D array.
     
  4. murado

    murado

    Joined:
    Jan 24, 2016
    Posts:
    6
    Works great jeffreyschoch! i totaly forgot about the Pysics2D. Thank you so much. Here is what i got now:

    float xpos = Random.Range(15, -15);
    float ypos = Random.Range(15, -15);

    if (Physics2D.OverlapCircle(new Vector2(xpos,ypos), 1))
    {
    Debug.Log("found something at that position");
    }

    else
    {
    Instantiate(powerup1, new Vector2(xpos, ypos), transform.rotation);
    }