- Home /
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 :( Help?
Answer by syclamoth · Oct 21, 2011 at 05:10 AM
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.
Do you want it to poll at random intervals? Or do you want it to wait a random time after it has detected people, and then do the generation bit? I'm not sure what you are asking here. Depending on how you do it, the counter can act however you need it to!
I'm talking about making it wait after it has detected the people, and before it has done WhenGenerate(). And I want it to wait a random amount of time before calling WhenGenerate()
Well then, that would be a bit different, but not very different. Ins$$anonymous$$d of just calling WhenGenerate, put it inside a coroutine, like this-
IEnumerator WaitAndGenerate()
{
yield new WaitForSeconds(Random.Range(5, 10));
if(CheckForPeople())
{
WhenGenerate();
}
}
Then put your proximity detection bit into a separate script, like this-
bool CheckForPeople(){
// the code from earlier, ending with
return peopleNear;
}
Then, probably don't put it in Update, make it trigger when the player meets certain conditions.
Answer by BerggreenDK · Oct 22, 2011 at 07:10 PM
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.