Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Attracting tagged rigidbodies

Discussion in 'Scripting' started by Holocene, Aug 30, 2011.

  1. Holocene

    Holocene

    Joined:
    Feb 21, 2009
    Posts:
    347
    I'd like to modify this script to only effect an object tagged as "target".
    Any ideas?

    Thanks,

    Greg


    Code (csharp):
    1. var radius = 30.0;
    2. var power = -90.0;
    3. function Update () {
    4. // Applies an explosion force to all nearby rigidbodies
    5. var explosionPos = transform.position;
    6. var colliders : Collider[] = Physics.OverlapSphere (explosionPos, radius);
    7.  
    8. for (var hit in colliders) {
    9. if (!hit)
    10. continue;
    11.  
    12. if (hit.rigidbody)
    13. {
    14. hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 0.0);
    15. }
    16. }
    17. }
     
    Last edited: Aug 30, 2011
  2. Eiznek

    Eiznek

    Joined:
    Jun 9, 2011
    Posts:
    374
    Can't you just check hit.tag.CompareTag("whateverTagIWantToHit) then apply the AddExplosionForce
     
  3. Rafes

    Rafes

    Joined:
    Jun 2, 2011
    Posts:
    764
    That would be the slow way to do it. If you are able to use layers, OverlapSphere can take a layerMask, which will return anything hit in the mask.

    The docs are flawed and don't make this obvious. It looks like the default is all layers if you don't provide this. Even if you DO need to use tags for some reason, you can still cut back on the number of objects processed by using a more general layer setup.
     
  4. Holocene

    Holocene

    Joined:
    Feb 21, 2009
    Posts:
    347
    Thanks for your help, guys. I went with:

    Code (csharp):
    1. if (hit.collider.gameObject.tag == "target")

    This does exactly what I want. Here is the final code I am using to attract tagged, rigidbody objects:

    Code (csharp):
    1. var radius = 30.0;
    2. var power = -90.0;
    3. function Update () {
    4. // Applies an explosion force to all nearby rigidbodies
    5. var explosionPos = transform.position;
    6. var colliders : Collider[] = Physics.OverlapSphere (explosionPos, radius);
    7.  
    8. for (var hit in colliders) {
    9. if (!hit)
    10. continue;
    11.  
    12. if (hit.collider.gameObject.tag == "target")
    13.  
    14.  
    15.  
    16.  
    17. {
    18. hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 0.0);
    19. }
    20. }
    21. }