I have a method as below
public void RequestTPCost(Action<int> callback, Action<int> enemyCallback)
{
if (OnTPSelectionNeeded == null)
{
callback?.Invoke(0);
enemyCallback?.Invoke(0);
return;
}
if (TurnSystem.Instance.IsPlayerTurn())
{
//Player turn use shooting unit is selected and target is enemy
OnTPSelectionNeeded?.Invoke(this, new TPSelectionInfo()
{
callback = callback,
enemyCallback = enemyCallback,
TPAvailable = selectedUnit.GetTacticalPoints(),
enemyTPAvailable = targetUnit.GetTacticalPoints(),
});
}
else
{
OnTPSelectionNeeded?.Invoke(this, new TPSelectionInfo()
{
callback = callback,
enemyCallback = enemyCallback,
TPAvailable = targetUnit.GetTacticalPoints(),
enemyTPAvailable = selectedUnit.GetTacticalPoints()
});
}
}
and I use it elsewhere like this
private void NextState()
{
switch (state)
{
case State.Aiming:
state = State.Choosing;
stateTimer = 0.1f;
UnitActionSystem.Instance.RequestTPCost(ConfirmTPCost,
ConfirmEnemyTPCost);
break;
case State.Choosing:
state = State.Shooting;
float shootingStateTime = 0.1f; //Not a frame
stateTimer = shootingStateTime;
break;
case State.Shooting:
state = State.Cooloff;
float coolOffStateTime = 0.5f;
stateTimer = coolOffStateTime;
Debug.Log("Shooting");
break;
case State.Cooloff:
ActionComplete();
break;
}
}
private void ConfirmTPCost(int value)
{
Debug.Log($"TP = {value}");
NextState();
}
private void ConfirmEnemyTPCost(int value)
{
Debug.Log($"EnemyTP = {value}");
//NextState();
}
Now I want to check if ConfirmTPCost < ConfirmEnemyTPCost
but am not sure how to simply do that.
I have a roundabout way using events and more UnityActionSystem
functions to call the instance and work through that but it seems very clunky and prone to breaking. Is there a better way to get these values and check which is more?
CodePudding user response:
var cost = 0;
var enemyCost = 0;
UnitActionSystem.Instance.RequestTPCost(i => cost = i, i => enemyCost = i);
Debug.Log($"TP = {cost}");
Debug.Log($"EnemyTP = {enemyCost}");
if (cost < enemyCost)
{
//Do your stuff here
}
CodePudding user response:
As said it sounds like there is actually some asynchronous parts involved.
So you either will want to properly implement async
and await
patterns and wait for both values to be available.
Or alternatively you could somewhat fake that behavior using e.g. nullables and a local function ike
int? cost = null;
int? enemyCost = null;
UnitActionSystem.Instance.RequestTPCost(i =>
{
cost = i;
if(enemyCost != null)
{
Validate();
}
}, i =>
{
enemyCost = i;
if(cost != null)
{
Validate();
}
});
// Can be a local function
// otherwise pass in the two int values via parameters
void Validate()
{
Debug.Log($"TP = {cost.Value}");
Debug.Log($"EnemyTP = {enemyCost.Value}");
if (cost.Value < enemyCost.Value)
{
//Do your stuff here
}
}
Idea here: No matter which of both callbacks fires first, it is ignored and only for the second one both values are already available and the actual handler method can be invoked