Search Unity

How do I select/swap networks at run time?

Discussion in 'ML-Agents' started by i-make-robots, Aug 27, 2022.

  1. i-make-robots

    i-make-robots

    Joined:
    Aug 27, 2017
    Posts:
    17
    I'm working on a network that teaches a quadruped to roll over.
    in a separate network, the quadruped knows how to walk towards a goal.

    I'd like to run these from a game and swap them in the right context.

    How, please?
     
  2. kokimitsunami

    kokimitsunami

    Joined:
    Sep 2, 2021
    Posts:
    25
    I've done that for changing difficulty level for my game setting. Switching NN models on runtime can be implemented by using SetModel method as shown in the sample code below:
    Code (CSharp):
    1. using Unity.MLAgents;
    2. using Unity.MLAgents.Policies;
    3. using Unity.Barracuda;
    4.  
    5. // Difficulty Levels
    6. public enum BattleMode
    7. {
    8.    Easy,
    9.    Medium,
    10.    Hard
    11. }
    12.  
    13. // Unity.Barracuda.NNModel class
    14. public NNModel easyBattleBrain = "BossBattle-easy.onnx";
    15. public NNModel mediumBattleBrain = "BossBattle-medium.onnx";
    16. public NNModel hardBattleBrain = "BossBattle-hard.onnx";
    17.  
    18. // Should match with Agent's Behavior Name in Unity's UI
    19. public string behaviorName = "BossBattle";
    20.  
    21. public void setDifficulty(BattleMode mode, Agent agent)
    22. {
    23.    switch (mode)
    24.    {
    25.        case BattleMode.Easy:
    26.            agent.SetModel(behaviorName, easyBattleBrain);
    27.            break;
    28.        case BattleMode.Medium:
    29.            agent.SetModel(behaviorName, mediumBattleBrain);
    30.            break;
    31.        case BattleMode.Hard:
    32.            agent.SetModel(behaviorName, hardBattleBrain);
    33.            break;
    34.        default:
    35.            break;
    36.    }
    37. }