I have lists to track which of my agents are selected to take action. Just recently, a nasty WTF showed itself. Somehow, during Start, just after I set a leader agent the data vanishes. Console records the operation succeeded, then a nanosecond later, Genie-Poof!!!
It is a short script, independent of any outside manipulation other than when the RankedUnit class registers with this class.
public class Selector : MonoBehaviour
{
public static Selector Instance { get; private set; }
InputControl control = null;
RankedUnit leader = null;
List<RankedUnit> rankedUnitList = new();
List<RankedUnit> selectedList = new();
private void Awake()
{
if (Instance != null)
{
Debug.LogError("There's more than one Selector instance. " + transform + " :: " +
Instance + "Redundent instance destroyed.");
Destroy(gameObject);
return;
}
Instance = this;
control = new(); control.Enable();
}
private void Start()
{
OrderUnitsByRank();
if (leader == null)
{
SetLeader(rankedUnitList[0]);
}
foreach (RankedUnit unit in rankedUnitList)
{
if (selectedList.Contains(unit) == false)
{
selectedList.Add(unit);
}
}
Debug.Log("leader = " + leader);
/* Success */
}
public void RegisterUnit(RankedUnit unit)
{
rankedUnitList.Add(unit);
}
void OrderUnitsByRank()
{
rankedUnitList.Sort((leftHand, rightHand) => leftHand.rank.CompareTo(rightHand.rank));
selectedList.Sort((leftHand, rightHand) => leftHand.currentRank.CompareTo(rightHand.currentRank));
}
public void UnregisterUnit(RankedUnit unit)
{ rankedUnitList.Remove(unit); }
public void SetLeader(RankedUnit player)
{
leader = player;
if (selectedList.Contains(player) == false)
{ selectedList.Add(player); }
}
public RankedUnit GetLeader()
{
if (leader == null)
{
Debug.Log("Major Tom?....");
}
/* Fail */
return leader;
}
private void OnDisable()
{
control.Disable();
control = null;
instance = null;
}
}
That’s about it.