- Home /
How to detect range of multiple gameobjects?
I am trying to create a script to where when the user comes within range of any of the objects, then the user may press "Spacebar" to open. I've searched for answers to similar questions but they don't help. Mostly the code is just "Here it works trust me" so I can't fully understand any of it because there is random spawn code and all that in the middle of what i need. And its not even in C#. Anyway. I need help with this, i've searched the references, answers, and just can't find what I am looking for.
Concept: Player is within range, now we can do something(Place code there).
MyScript:
using UnityEngine;
using System.Collections;
public class TriggerDetection : MonoBehaviour
{
//--------------------------
//Player's Position.
public Transform player;
//Set the range.
int range = 20;
//--------------------------
void Update()
{
//If the player comes within range of us.
if (Vector3.Distance(transform.position, player) < range)
{
//Do something
Debug.DrawLine(transform.position, player, Color.red);
}
}
}
Well I was wanting this script to be attatched to the item, and have an option in the inspector to drag on the player. For example if I want to add a chest in game, drag the player into a slot on the inspector and then if the player goes close to that chest he will be able to open it. This setup would make it easy to add in other trigger items such as doors, gates, portals, anything like that you know
Never$$anonymous$$d, I am an idiot. OnTriggerEnter is exactly what I was trying to do lol. I been up way too long obviously. Thank you
Answer by getyour411 · Jan 28, 2014 at 11:17 PM
Before you go too far down this road, why aren't you using OnTriggerEnter?
Your answer
Follow this Question
Related Questions
How to detect range? 2 Answers
How to use a script on multiple gameobjects, then change a variable for one of them, not the other. 3 Answers
How would I have a volume bar in multiple places? 1 Answer
Checking if multiple GameObjects do what one has to.... 1 Answer
Problem with multiple gameobjects using same script. 0 Answers