When i destroy in script a game object with Script named “Character”, script have to clear and sort the list. But it haven’t
if (Type == UnitType.Fighter && fightManager.CanAttack(Pos, charScript.Pos, charScript.team))
{
print("I attacked!");
Destroy(charScript.gameObject);
print(fightManager.fighters.Count);
fightManager.Sort();
}
public void Sort()
{
fighters.Clear();
fighters = GameObject.FindObjectsOfType<Character>().ToList();
fighters = fighters.OrderBy(f => f.Speed).ToList();
fighters.Reverse();
}
and i have this: http://www.filedropper.com/scr
Please help.
Well, considering that you create new lists, Clear isn’t your problem here.
public void Sort()
{
//you clear the list, ok
fighters.Clear();
//but then you create a whole new list
fighters = GameObject.FindObjectsOfType<Character>().ToList();
//and now you create YET ANOTHER list
fighters = fighters.OrderBy(f => f.Speed).ToList();
//and now you reverse that 2nd list you created
fighters.Reverse();
}
Now, I’m not even sure what you mean by it’s ignoring clear… Clear should empty the list. But you immediately create a brand new FULL list. So yeah, that new list isn’t going to be empty.
Do you mean that the new list contains the Character that was just destroyed?
Here’s the thing, Destroy doesn’t actually occur immediately, it is deferred to later in the frame. So methods like ‘FindObjectsOfType’ might still return the object, even though it’s going to be destroyed shortly.
Oh, and note, there is a version of ‘Sort’ that doesn’t require you creating all new lists…
And you can sort in reverse so that you don’t have to call the Reverse method.
2 Likes
Indeed, Destroy is deferred to the end of the frame, so any Finds will 100% still return the object. Also, why not just remove the appropriate item from the list instead of going through all that?
–Eric
2 Likes
[quote=“newGuyInThat, post:4, topic: 628857, username:newGuyInThat”]
I am so stupid, thanks!
[/quote]I prefer the term, “inexperienced”.
1 Like