Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question 2D ML Agents Code not working

Discussion in 'ML-Agents' started by Magenta3572, Jan 21, 2024.

  1. Magenta3572

    Magenta3572

    Joined:
    Aug 3, 2023
    Posts:
    1
    For some reason, the code doesnt have any method groups, but when I use it in Unity, it shows an errror saying that it's unable to assign to OnEpisodeBegin because it's a method group. Is anyone able to fix this?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.MLAgents;
    5. using Unity.MLAgents.Actuators;
    6. using Unity.MLAgents.Sensors;
    7.  
    8. public class AgentScript : Agent
    9. {
    10.     public float moveSpeed = 5f;
    11.     public float broadcastRange = 5f;
    12.  
    13.     void Start()
    14.     {
    15.         OnEpisodeBegin += ResetAgent;
    16.     }
    17.  
    18.     void ResetAgent()
    19.     {
    20.         transform.position = new Vector3(0f, 0f, 0f);
    21.         transform.rotation = Quaternion.identity;
    22.     }
    23.  
    24.     public override void OnActionReceived(ActionBuffers actions)
    25.     {
    26.         Vector2 moveDirection = new Vector2(actions.ContinuousActions[0], actions.ContinuousActions[1]).normalized;
    27.         GetComponent<Rigidbody2D>().velocity = moveDirection * moveSpeed;
    28.         BroadcastMessageToOthers();
    29.     }
    30.  
    31.     public override void CollectObservations(VectorSensor sensor) => sensor.AddObservation(transform.position);
    32.  
    33.     void BroadcastMessageToOthers()
    34.     {
    35.         Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, broadcastRange);
    36.         foreach (Collider2D collider in colliders)
    37.             if (collider.gameObject != gameObject)
    38.                 collider.gameObject.SendMessage("OnBroadcastReceived", SendMessageOptions.DontRequireReceiver);
    39.     }
    40. }
     
  2. smallg2023

    smallg2023

    Joined:
    Sep 2, 2018
    Posts:
    154
    override the onepisodebegin function in your script instead

    Code (CSharp):
    1.  public override void OnEpisodeBegin()
    2.     {
    3.         ResetAgent();
    4.     }