Kaunet
1
Hello,
I have GameObjects in an array found by a tag in a certain distance. I have an enum of conditions:
public enum Condition
{
Critical = 10,
Moderate = 25,
Barely = 50
}
I want to sort them by most important ones e.g.
Barely
Barely
Moderate
Critical
and after that do something with them from 1st to last. How can I achieve that? Would appreciate if anyone would explain the best approach for this, here is the code:
protected void CheckForCloseBodies(string tag, float minimumDistance)
{
GameObject[] goWithTag = GameObject.FindGameObjectsWithTag(tag);
var newCurrentHealth = 0.0f;
for (int i = 0; i < goWithTag.Length; ++i)
{
var bodyDamageHandler = goWithTag*.GetComponent<vp_DamageHandler>(); // Dead Bodys*
var bodysCondition = goWithTag*.GetComponent();*
var convertedHealth = bodysCondition.checkScavangeCondition();
if (Vector3.Distance(transform.position, goWithTag*.transform.position) <= minimumDistance)*
{
if (transform.position != goWithTag*.transform.position)*
{
if (bodyDamageHandler.IsDead == true)
{
if (bodysCondition.AbleToScavenge == true)
{
newCurrentHealth = PlayerDamageComponent.CurrentHealth + convertedHealth;
if (goWithTag.Length > 1)
{
// HERE IT SHOULD SORT THEM
}
else
{
if (newCurrentHealth <= PlayerDamageComponent.MaxHealth)
{
Debug.Log(PlayerDamageComponent.CurrentHealth = newCurrentHealth);
bodysCondition.scavangableHealth = 0.0f;
}
else
{
if (!isFullHealth)
{
bodysCondition.scavangableHealth = newCurrentHealth - PlayerDamageComponent.MaxHealth;
newCurrentHealth = newCurrentHealth - bodysCondition.scavangableHealth;
}
}
}
}
}
}
}
}
}
Thank you
fafase
2
Maybe your design could be improved. Ordering can be expensive and in your case, you are not really ordering, more likely arranging by type (ok quite similar).
I would rather have 3 different lists each containing the corresponding type. If an object is changing its type then it is also changing the collection it belongs to.
private Condition condition = Condition.None; // or any default
private Manager manager = null; // Get a ref in start
public Condition ObjCondition {
get{return condition;}
set{
if(condition!=value){
condition = value;
List<GameObject> typeList = manager.GetList(value);
typeList.Add(this.gameObject);
}
}
}
in the manager:
private Dictionary<Condition, List<GameObject>> dict = new Dictionary<Condition, List<GameObject>>();
void Awake(){
dict.Add(Condition.Critical, new List<GameObject>());
// Same for others
}
public List<GameObject> GetList(Condition condition)
{
return dict[condition];
}
The needing methods get a reference to the list by condition and only those objects so you don’t even have to check when it changes condition in the collection.