- Home /
Find Nearest Object from an Array of Transforms
Hi,
I have an array of Transforms (Each with it's own unique name), and I am trying to get the name of the Transform that is nearest to another Object.
The variable I have used to setup the array is:
var attackerClonesArray = new List.<Transform>();
I have tried adapting various solutions (for example Eric5r5's comments in this post: http://answers.unity3d.com/questions/15229/geting-the-closest-object-from-a-array.html) but I have had little luck.
I understand that I will have to create another array to sort through, but this seems to cause my problems. It's almost like I am creating the wrong type or structure of array if that makes sense.
Any advice will be most welcome!
Thanks
Paul
Answer by whydoidoit · Sep 30, 2012 at 03:20 PM
You can do it with Linq if you like:
import System.Linq;
...
var nearest = yourArrayOfTransforms.OrderBy(function(t) { return (thingToBeCloseTo.position - t.position).sqrMagnitude; }).First();
For best performance cache thingToBeCloseTo.position before the line:
var checkPosition = thingToBeCloseTo.position;
var nearest = yourArrayOfTransforms.OrderBy(function(t) { return (checkPosition - t.position).sqr$$anonymous$$agnitude; }).First();
Hi $$anonymous$$ike,
Thanks for the suggestion. I am having problems implementing it. Here is what I have so far:
[code]
import System.Linq;
var thingToBeCloseTo = Vector3();
function Update() {
thingToBeCloseTo = transform.position;
var nearest = attackerClonesArray.OrderBy(function(t) { return (thingToBeCloseTo - t.position).sqr$$anonymous$$agnitude; }).First(); }
[/code]
I am getting the following error code: $$anonymous$$issing$$anonymous$$ethodException: $$anonymous$$ethod not found: 'System.Collections.Generic.List`1[[UnityEngine.Transform, UnityEngine, Version=0.0.0.0, Culture=neutral, Public$$anonymous$$eyToken=null]].OrderBy'.
It late now so I am maybe being a bit stupid >_<
Also how do you specify if a section is code here in the comment section?
Thanks!
Do you have stripping turned on? Are you using a very low version of the .NET mscorlib?
Er... I have no idea about what you just referenced lol!
I just looked up StrippingLevel and I have not setup anything to do that. So I would say whatever the default is.
As for a very low level .NET mscorlib, sorry but I have no idea, so I would guess that as a no also.
Sorry!
Your answer
Follow this Question
Related Questions
Resize Array based on distance. 2 Answers
Storing a variable and it's name 3 Answers
Can an Instance Array Recognize Separately Named Instances? 0 Answers
Sort - OrderBy GameObjects by Distance 2 Answers
List.Sort with IComparer 2 Answers