Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  4. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  5. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  6. 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:
    12
    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,801
    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,241
    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:
    12
    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);
    }