Cysharp / UniTask

Provides an efficient allocation free async/await integration for Unity.
MIT License
8.23k stars 844 forks source link

Understanding CancellationToken propagation downwards #349

Closed codemonkeynorth closed 2 years ago

codemonkeynorth commented 2 years ago

given the setup below I'm trying to understand where I would create cancellation tokens so that game actions could be cancelled when the game object is destroyed. Do I need to pass the token all the way down through the objects from the MonoBehaviour?

(CancellationSource code not added yet)


// MONOBEHAVIOUR
class GameActionRunner : MonoBehaviour
{
  [SerializeReference] public List<GameAction> GameActions = new();

  void Start()
  {
    GameActionSystem system = new GameActionSystem(GameActions);
    var gameActionsStartState = new GameActionsStartState(system);
    ..
    ..
    // calls state’s Enter()
    system.SetState(gameActionsStartState).Forget(); // or await? 

  }
}

// FSM STATE
class GameActionsStartState : State
{
  GameActionSystem system;

  public GameActionsStartState(GameActionSystem)
  {
    this.system = system;
  }

  public async UniTask Enter()
  { 
    foreach(var action in system.GameActions) 
    {
       await action.Run();
    }
  }
}

// ASYNC ACTION (wait action, cutscenes, animations etc)
[Serializable]
public class GameAction 
{ 
  public SomeData data; 

  public async UniTask Run()
  {
     // await async ops 
     // animations etc
     // send data off to processors (awaits response)

     var status = await DataProcessor.Process(this.data)
  }
}

Also the data processors mentioned in the last class can mark incoming data as Complete / Cancelled if the data processor itself is cancelled elsewhere but presumably I'd just return the status

github-actions[bot] commented 2 years ago

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.