I created a targetsList class which has a sorting method using the .net Sort() function
Everything is goo except for
“TargetsList.Asc' does not implement interface member
System.Collections.IComparer.Compare(object, object)'”
and tl*.distance returns a "object doesn’t contain a definition for distance…*
```
*using System;
using System.Collections;
using UnityEngine;
class TargetsList
{
public bool sorted = false;
public ArrayList list = new ArrayList();
public struct target
{
public int health;
public int power;
public float distance;
public Transform transform;
}
public TargetsList FindClosest(float maxDistance)
{
ArrayList tl = new ArrayList();
if (sorted)
{
tl = list;
for (int i =0; i< tl.Count; i++)
{
if (tl[i].distance >maxDistance) return;
}
tl.TrimToSize(i);
}
return tl;
}
public void Sort()
{
list.Sort(0, list.Count, new Asc());
}
public class Asc : IComparer
{
public int Compare(target x, target y)
{
return (x.distance).CompareTo(y.distance);
}
}
}*
```
I haven’t looked at your code fully and I am heading to bed finally, but like I mentioned quickly on IRC (I should have spent more time explaining it, sry) you need to box the arraylist to access members of stored objects…
Like this:
((TargetList)tl[i]).distance = 5.0F;
//so:
((MyObjectType)myArrayList[index]).myMember
Took me a while to find that out the first time too.
HTH,
-Jeremy
Thanks, object types are brutal…
Here is what came up with and it’s giving me a hard time on the (Target)o, it wants a TargetsList but I need the .distance … what’s the secret sauce?
using System;
using System.Collections;
using UnityEngine;
class TargetsList
{
public bool sorted = false;
public ArrayList list = new ArrayList();
public struct Target
{
public int health;
public int power;
public float distance;
public Transform transform;
}
public TargetsList FindClosest(float maxDistance)
{
TargetsList tl = new TargetsList();
if (sorted)
{
tl.list = list;
int i = 0;
foreach (object o in tl.list)
{
if (((Target)o).distance > maxDistance) return;
i++;
}
tl.list.RemoveRange(i,tl.list.Count-i);
}
return tl;
}
public void SortDistance()
{
list.Sort(0, list.Count, new Asc());
}
public class Asc : IComparer
{
public int Compare(Target x, Target y)
{
return (x.distance).CompareTo(y.distance);
}
}
}
You switched from a for loop to a foreach loop, and o is an object, so you don’t need that boxing anymore.
foreach (object o in tl.list) //object
{
if (((Target)o).distance > maxDistance) return;
i++;
}
See, in that loop you use the contents of tl.list as object.
To handle that properly, cast o as your type normally without the boxing.
You really want to go through some tutorials on types and loops, etc, as hack-and-slash refactoring will just drive you crazy and mess up your code. It’s a pain to do, but the time spent will really help in the long-run 
-Jeremy