Check distance between multiple objects

What I’m trying to do is to make a script in C# that uses a function when the distance of any “People” is closer than 0.5 to the object this script is attached to. This is the (important part of) the script.

using UnityEngine;
using System.Collections;

public class PersonScript : MonoBehaviour {
	
	public Transform[] People;
	
	void WhenGenerate(){		
		Debug.Log("Generating...");		
	}
	
	void Update () {	
		if(Vector3.Distance(People.position, transform.position) < 0.5){
			WhenGenerate();
		}
	}
}

It doesn’t work :frowning:
Help?

Given that you already have an array full of people, the rest is easy!

Where you have

if(Vector3.Distance(People.position, transform.position) < 0.5){
    WhenGenerate();
}

instead, do this:

bool peopleNear = false;
foreach(Transform person in People)
{
    if(Vector3.Distance(person.position, transform.position) < 0.5f)
    {
        peopleNear = true;
        break;
    }
}
if(peopleNear)
{
    WhenGenerate();
}

You almost had it, it’s just that you need loops to be able to access every member of a collection like that.

You could go another direction with your code.

In the Physics class, there is a function called CheckSphere that takes a radius as parameter.

http://unity3d.com/support/documentation/ScriptReference/Physics.CheckSphere.html

another approach could be this:

http://unity3d.com/support/documentation/ScriptReference/Physics.OverlapSphere.html

where you get a list of the colliders it overlaps.

Think of these functions as a cookie-cutter-shape that you place over your “world” and the inside of the form is your list of objects that matches your query.

I dont know if this function is more expensive than the other approach, but I would use it for a test, if I needed what you describe.