- Home /
Write values in list-like thing.
Hi guys!
The title may sound weird, but here is what i want. So in my game i have lots of objects and every object has a script called Info which contains a variable objectName. So how can i get this variable for every single object which is closer than some value to the player and make a list with the object. (Im making a space game and I got this idea from the EVE online UI)
Thanks. -Arnold
Physics.OverlapSphere() will find all the colliders withing a specific radius.
If you are sure that every object has this script, you can just create a new, built-in array the same size one as the array returned by OverlapSphere(). If any of the object don't have this script, then use a collection that can grow. I recommend a .NET generic List. You will find info on many collection types including a generic List here:
http://wiki.unity3d.com/index.php?title=Which_$$anonymous$$ind_Of_Array_Or_Collection_Should_I_Use?
You use GetComponent() to get the script from each collider in the array.
http://unitygems.com/script-interaction-tutorial-getcomponent-unityscript/
It takes some time to get your $$anonymous$$d wrapped around the concept, but you can do what you are seeking in just a line or two of code using LINQ. Some information on LINQ and Unity here:
Answer by chees502 · Aug 10, 2014 at 09:47 PM
If I am understanding your intention correctly. You could add a functionality on your info script to append itself to a static list. Doing it this way makes for better code than doing a search for all the GameObjects in the scene.
using System.Collections.Generic;
...
static IList<Transform> nearTargets=new List<Transform>();
Transform playerPosition;
float maxRange=10.0f;
bool inRange=false;
...
void FixedUpdate(){
float distance=Vector3.Distance(playerPosition.position,transform.position);
if(inRange){
if(distance>maxRange){
inRange=false;
//remove from list
nearTargets.Remove(transform);
}
}else{
if(distance<maxRange){
inRange=true;
//add to list
nearTargets.Add(transform);
}
}
}
then you can just dot into it from any other code file with info.nearTargets[x].position;
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Conversion of a C++ variable to UnityScript? 2 Answers
Timer help please 1 Answer
Unexpected Token BCE0043 0 Answers
Swipe in Unity3d 3 Answers