Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Finding a Collider's parent Game Object when using Physics.OverlapSphere

Discussion in 'Scripting' started by Phill7788, Jan 29, 2019.

  1. Phill7788

    Phill7788

    Joined:
    Mar 11, 2017
    Posts:
    1
    Hi all,
    I am using Unity 2018.2.13f1
    My script uses the Physics.OverlapSphere to find Colliders hitColliders. Then, I create a game object for the hitColliderObject. Here is my code.


    Code (CSharp):
    1. Collider[] hitColliders = Physics.OverlapSphere(center, explosionRadius);
    2.  
    3.         GameObject hitColliderObject = hitColliders.transform.parent.gameObject;

    However, I am getting an error under hitColliders.transform.parent.gameObject; The error is:

    Error CS1061: 'Collider[]' does not contain a definition for 'transform' and no extension method 'transform' accepting a first argument of type 'Collider[]' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Assembly-CSharp)

    Help would be very much appreciated,
    Thanks.
     
  2. Zalosath

    Zalosath

    Joined:
    Sep 13, 2014
    Posts:
    671
    That's because you're calling ".transform" on the entire array of items. You should instead loop over each item in the array and do it individually.
     
    Phill7788 likes this.
  3. jakejolli

    jakejolli

    Joined:
    Mar 22, 2014
    Posts:
    54
    Like so:

    If you're just checking hitColliderObject, you can use a foreach loop:
    Code (CSharp):
    1. Collider[] hitColliders = Physics.OverlapSphere(center, explosionRadius);
    2.  
    3. foreach(Collider hitCollider in hitColliders){
    4.      GameObject hitColliderObject = hitCollider.transform.parent.gameObject;
    5.      //Do some stuff here
    6. }

    But, if you're going to be changing hitColliderObject in any way, you'll need a for loop:
    Code (CSharp):
    1. Collider[] hitColliders = Physics.OverlapSphere(center, explosionRadius);
    2.  
    3. for(int i = 0; i < hitColliders.Length; i++)){
    4.      Collider hitCollider = hitColliders[i];
    5.      GameObject hitColliderObject = hitCollider.transform.parent.gameObject;
    6.      //Do some stuff here
    7. }
     
    Phill7788 likes this.