Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
Assistant
User
i have an EmptyObject called “Training Area”, in this object i have Player (Agent for ML Agents), Floor, WallTop, WallBottom, WallRight, WallLeft and all spawning foods.
ok, i copied my "Training Area" multiple times to get ML Agents training faster.
but it seems that the learning process is only on one, the very first agent. all the rest synchronously go to the upper right corner of the map with slight deviations.
after about 1000 steps, I have only one agent jerking in random directions, all the other agents just go into the wall, each in his own. it feels like there is not enough batch or buffer.
Based on your description and configuration, it could be that the agents are getting similar experiences during training, hindering their ability to learn effectively. The reason why all of them go into the wall could be because the network is not learning from multiple experiences. I have a few suggestions to improve your training:
User
Assistant
Your code looks good for the player and food interaction, but I have some suggestions to improve the learning process:
Normalize the observations.
In the script, normalize the observations relative to the spawn range by dividing the position values by . This will keep the input values between -1 and 1, making it easier for the neural network to learn.
User
Do not understand how to use the Ray Perception Sensor 2D component in MLAgents
Assistant
The Ray Perception Sensor 2D component is used to add raycasting perception capabilities to your ML Agents. It allows the agent to "see" its surroundings in a certain direction and detect objects with specific tags. This component is useful for providing information about objects around the agent without explicit positional data.
User
when circle collider 2d is on, my ray perception sensor 2d is not functioning
Assistant
The Ray Perception Sensor 2D component relies on raycasting, which might not work as expected with certain colliders. If you are experiencing issues with the Circle Collider 2D, you can try the following steps:
Create an additional child GameObject under the Player (Agent) that you will use for raycasting. Name it "RayCastOrigin" and reset its Transforms.
Move "RayCastOrigin" GameObject a bit above the agent's collider to ensure that its rays are not blocked by the Circle Collider 2D.
Select your "Player (Agent)" GameObject, find the Ray Perception Sensor 2D component in the Inspector, and assign the "RayCastOrigin" GameObject as its Transform.
Here's an illustration of the GameObject hierarchy:
Player (Agent)
Circle Sprite
RayCastOrigin
(other child GameObjects)
By doing this, the rays will originate from the "RayCastOrigin" GameObject above the agent's collider, avoiding interference with the Circle Collider 2D.
Remember to test different ray distances and directions to make sure the rays are reaching your objects correctly. If you still face issues, ensure that the "Food" GameObjects have the required tags assigned and the Ray Perception Sensor 2D has the correct tags listed in its "Detectable Tags' property.
User
Assistant
The Ray Perception Sensor observations are automatically added in ML-Agents after version 1.0.0, so there's no need to add them explicitly in the CollectObservations method. If you still have 0 observations during training, the MLAgents package in your project might be out-of-date. Double-check your ML-Agents version.
However, if you're using a version of ML-Agents less than 1.0.0, you need to include ray perception sensor observations explicitly in the method.
User
Assets\Scripts\PlayerController.cs(63,72): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'rayLength' and no accessible extension method 'rayLength' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\PlayerController.cs(63,97): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'rayAngles' and no accessible extension method 'rayAngles' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\PlayerController.cs(63,122): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'detectableTags' and no accessible extension method 'detectableTags' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Assistant
I apologize for the confusion. It seems you are using a newer version of ML-Agents. My provided solution was for an older version. In that case, you don't need to modify the CollectObservations method, as the Ray Perception Sensor observations are automatically included in ML-Agents version 1.0.0 or later.
If you have 0 observations during the training, please make sure you have properly configured the Ray Perception Sensor component in the Unity Inspector.
In the Unity Inspector, select your Player (Agent) game object.
In the Ray Perception Sensor 2D component, make sure you have added the required angles to the Ray Directions list.
Ensure that the Detectable Tags list has the correct tags that match your game objects' tags. For example, if your Food objects have the "Food" tag, make sure "Food" is in the Detectable Tags list.
Adjust the Ray Distance according to your scene setup to ensure the rays are long enough to reach other objects.
User
the rays are visible, the rays end where necessary, everything is fine in the plan of the rays. just shows 0 observations.
Assistant
I apologize for the confusion, and I appreciate your patience. Since the rays seem to be correctly set up, let's check if the observations are being used during training.
In your PlayerController.cs script, add [Observable] attribute to the Agent's script, just above the class definition:
using Unity.MLAgents.Sensors.Reflection;
[AddComponentMenu("")]
[Observable]
public class PlayerController : Agent
{
// ...
}
This attribute will make your Agent observable in the Unity Inspector, allowing you to see the generated observations.
Start your training environment using the Unity Editor "Play" button. While it is running, click on the "Training Area" GameObject in the hierarchy.
In the top right of the Inspector, click on the "Debug" view button.
User
Assets\Scripts\PlayerController.cs(8,2): error CS0592: Attribute 'Observable' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
Assistant
I apologize for the confusion once again. My previous response contained incorrect information. There is no Observable attribute in ML-Agents.
I misunderstood your initial question about "0 observations." It seems you are referring to the lack of observations showing up during training in the Unity Editor, not the actual learning process. In the Unity Editor, you may not see the observation count for Ray Perception Sensor 2D directly as it gets processed internally by ML-Agents. However, this doesn't mean that the sensor is not working.
As long as the rays appear correctly during play mode and the detectable tags are properly set up, the Ray Perception Sensor 2D should be contributing to your agent's learning experience. Please proceed with the training process using the following command, as previously suggested:
As long as there are no errors in the ML-Agents console during training, the agent should be learning using the raycast perception data. Monitor the agent's progress through the training.
User
i still get this error:
Fewer observations (0) made than vector observation size (42). The observations will be padded.
UnityEngine.Debug:LogWarningFormat (string,object[])
Unity.MLAgents.Sensors.VectorSensor:Write (Unity.MLAgents.Sensors.ObservationWriter) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs:56)
Unity.MLAgents.Policies.HeuristicPolicy:StepSensors (System.Collections.Generic.List1<Unity.MLAgents.Sensors.ISensor>) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs:133) Unity.MLAgents.Policies.HeuristicPolicy:RequestDecision (Unity.MLAgents.AgentInfo,System.Collections.Generic.List1<Unity.MLAgents.Sensors.ISensor>) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs:38)
Unity.MLAgents.Agent:SendInfoToBrain () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Agent.cs:1130)
Unity.MLAgents.Agent:SendInfo () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Agent.cs:1368)
Unity.MLAgents.Academy:EnvironmentStep () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Academy.cs:592)
Unity.MLAgents.AcademyFixedUpdateStepper:FixedUpdate () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Academy.cs:43)
Assistant
I apologize for the confusion, and I appreciate your patience. The error is happening due to an inconsistency in the observation size during the training.
Since the Ray Perception Sensor 2D is not manually included inside the CollectObservations method in newer ML-Agents versions, the expected behavior is that it automatically contributes to the observations internally. However, it seems to be a problem while training with the Heuristic methods in play mode.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I cannot directly create the game for you, but I can help you by providing a step-by-step guide to achieve what you want. Make sure you have already followed the installation process of ML-Agents from their GitHub repository.
Create a new 2D Unity project.
In the Project window, go to Assets > ML-Agents > Examples and duplicate the "2D" example within it. Rename the folder "Simple2DGame".
Open the duplicate example.
Replace the Area Plane sprite with a new sprite, e.g., a simple square for a top view. Set the size according to your preferences.
Delete the Goal and Wall objects of the game.
Create a new Circle sprite in the Sprites folder, and use this sprite for the character and food objects.
Resize and set the color of the new circle sprites.
Update the prefabs:
a. As the ML-Agents use prefabs defined within the script, change the Player (Agent) prefab by duplicating the existing Agent object from the example scene, removing unnecessary components (like the Script in the Inspector) and adding a 2D Rigidbody with the Gravity Scale set to 0.
b. Create a new prefab in the Prefabs folder for the FoodCircle and make sure that the prefab has a Circle Collider 2D with the Is Trigger option checked.
Modify the Area script:
a. Remove the references to Goal and Wall.
b. Add a public GameObject FoodCirclePrefab, and instantiate it randomly around the player character using a helper method.
c. Update the code that resets the Agent in the Done method to include the removal of existing FoodCircle objects and the creation of new ones.
Design a new Agent script:
a. Create a new C# script for the circle character, name it "CircleController".
b. In the script, inherit from Unity.MLAgents.Agent.
c. Implement the methods OnEpisodeBegin, CollectObservations, Heuristic and OnActionReceived according to your desired behaviour.
d. In OnEpisodeBegin, reset the agent's position.
e. In CollectObservations, add the necessary observations using AddObservation method. For example, the current position of the agent, the relative position of the food, etc.
f. In OnActionReceived, implement the character's movement based on the received actions.
g. In the Heuristic, create an array of floats to process keyboard input (WASD), record the actions and then add them to the actionsOut list.
h. Add a method to handle the collision of the Agent with a FoodCircle, use AddReward in the ML-Agents to give the Agent extra rewards for this behaviour, and call EndEpisode.
Attach the CircleController script to the Player (Agent) object.
Open the Project > Assets > Simple2DGame > ML-Agent Examples folder and duplicate the "2d" scene. Rename it to "Simple2DGame".
Open the "Simple2DGame" scene, delete unnecessary game objects and modify the scene to fit the new game.
In the ML-Agent folder, duplicate an existing configuration file (e.g., "3DBall.yaml") and rename it to "Simple2DGame.yaml". Modify its contents to match your Agent and training scenario (observe, action space, etc.).
Open the file Project > Assets > ML-Agents > Plugins > Computer > mlagents_override.yaml and paste the path to the Simple2DGame.yaml inside the behavior_specs list.
Open a terminal/command prompt and navigate to your Unity project folder, then run:
This command will start the training with the given configuration and run ID.
After setting up the training scenario properly, you might face issues with the control mechanism between training and agents. You can bypass this using the Academy.Instance.IsCommunicatorOn property, allowing the manual agent control.
To switch between the two, use a simple condition like this within the Heuristic method:
if (!Academy.Instance.IsCommunicatorOn)
{
// Process input and actions manually for keyboard control.
}
When everything is set up correctly, you will be able to train your agent and switch to keyboard control when needed.
Increase batch_size and buffer_size.
Since you have multiple agents, increasing the batch_size and buffer_size in your yaml configuration might help improve training. Try increasing them as follows:
batch_size: 64
buffer_size: 2048
Make the food positions more random.
Ensure that food is spawning in different positions for every agent. If the agents are not having diverse experiences, it will be hard for them to learn properly. If the area is the same for all agents, you can try randomizing the initial positions of the agents.
Randomize agent starting positions.
As mentioned earlier, randomizing the starting position of the agents can improve their learning. Inside your CircleController script, modify the OnEpisodeBegin method:
public override void OnEpisodeBegin()
{
// Reset the agent's position
float randomX = UnityEngine.Random.Range(-areaSize.x / 2, areaSize.x / 2);
float randomY = UnityEngine.Random.Range(-areaSize.y / 2, areaSize.y / 2);
transform.localPosition = new Vector3(randomX, randomY, 0);
}
Add rewards for moving away from the walls.
One reason agents might be getting stuck is that they don't have a clear motivation to avoid the walls. You can add a reward signal inside OnActionReceived() method after calculating the new position of the agent but before applying it:
public override void OnActionReceived(ActionBuffers actionBuffers)
{
float moveX = Mathf.Clamp(actionBuffers.ContinuousActions[0], -1, 1);
float moveY = Mathf.Clamp(actionBuffers.ContinuousActions[1], -1, 1);
Vector3 newPosition = transform.localPosition + new Vector3(moveX, moveY, 0f) * Time.deltaTime * moveSpeed;
// Add a reward signal for moving away from the walls
if (Mathf.Abs(newPosition.x) < areaSize.x / 2 && Mathf.Abs(newPosition.y) < areaSize.y / 2)
{
AddReward(0.001f);
}
// Update agent position
transform.localPosition = newPosition;
}
Try applying some of these suggestions and monitor changes in the agent's behavior during the learning process. Experiment with different reward signals and positions to create a more diverse learning experience for the agents.
here's my FoodSpawner.cs which attached to "Training Area":
using System.Collections;
using UnityEngine;
using Unity.MLAgents;
public class FoodSpawner : MonoBehaviour
{
public GameObject foodPrefab;
public int numberOfFoods;
public float spawnRange;
public float maxEpisodeTime = 30f; // in seconds
private float episodeTimer;
private PlayerController player;
private void Start()
{
player = GetComponentInChildren<PlayerController>();
if (player != null)
{
player.SetFoodSpawner(this);
}
SpawnFood();
episodeTimer = maxEpisodeTime;
}
void Update()
{
ManageEpisode();
}
public void SpawnFood(int customNumberOfFoods = -1)
{
// Delete any remaining food
foreach (var food in GetComponentsInChildren<Food>())
{
Destroy(food.gameObject);
}
int foodCount = customNumberOfFoods != -1 ? customNumberOfFoods : numberOfFoods;
for (int i = 0; i < foodCount; i++)
{
Vector3 spawnPosition = transform.position + new Vector3(Random.Range(-spawnRange, spawnRange), Random.Range(-spawnRange, spawnRange));
GameObject newFood = Instantiate(foodPrefab, spawnPosition, Quaternion.identity);
newFood.transform.SetParent(transform); // Set the parent to the current "Training Area"
newFood.transform.localScale = Vector3.one;
}
}
void ManageEpisode()
{
episodeTimer -= Time.deltaTime;
int remainingFoodCount = GetComponentsInChildren<Food>().Length;
if (episodeTimer <= 0 || remainingFoodCount == 0)
{
player.ResetPlayerEpisode();
SpawnFood();
episodeTimer = maxEpisodeTime;
}
}
}
here's my PlayerController.cs:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
public class PlayerController : Agent
{
public float speed = 5f;
private Rigidbody2D rb;
private FoodSpawner foodSpawner;
private Vector3 initialPosition;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
initialPosition = transform.position;
}
public override void OnEpisodeBegin()
{
rb.velocity = Vector2.zero;
transform.position = initialPosition; // Reset player position to the initial position
}
public override void CollectObservations(VectorSensor sensor)
{
sensor.AddObservation(rb.velocity.x);
sensor.AddObservation(rb.velocity.y);
if (foodSpawner != null)
{
int foodIndex = 0;
int totalFoodCount = foodSpawner.numberOfFoods;
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
sensor.AddObservation(food.transform.position.x);
sensor.AddObservation(food.transform.position.y);
foodIndex++;
}
// Pad zeros if not enough food
for (int i = foodIndex; i < totalFoodCount; i++)
{
sensor.AddObservation(0);
sensor.AddObservation(0);
}
}
}
public override void OnActionReceived(ActionBuffers actions)
{
float moveHorizontal = actions.ContinuousActions[0];
float moveVertical = actions.ContinuousActions[1];
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb.AddForce(movement * speed);
SetReward(-Time.fixedDeltaTime);
}
public void AddRewardOnEatingFood()
{
AddReward(1f);
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var continuousActionsOut = actionsOut.ContinuousActions;
continuousActionsOut[0] = Input.GetAxis("Horizontal");
continuousActionsOut[1] = Input.GetAxis("Vertical");
}
public void ResetPlayerEpisode()
{
EndEpisode();
transform.position = initialPosition; // Reset player position to the initial position
rb.velocity = Vector2.zero;
}
public void SetFoodSpawner(FoodSpawner spawner)
{
foodSpawner = spawner;
}
}
here's my Food.cs, which attached to food prefab:
using UnityEngine;
public class Food : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
PlayerController playerController = collision.GetComponent();
if (playerController != null)
{
playerController.AddRewardOnEatingFood();
Destroy(this.gameObject);
}
}
}
}
PlayerController.cs
foodSpawner.spawnRange
Modify the CollectObservations method in the PlayerController.cs inside the foreach loop as follows:
Randomize player's starting position.
To provide more diverse experiences for the agent, randomize the starting position of the player instead of keeping it fixed at initialPosition. Modify the OnEpisodeBegin method inside the PlayerController.cs script:
Limit the player's movement.
To prevent the player from getting stuck in the walls, limit the player's movement to the spawn range. Modify the OnActionReceived inside the PlayerController.cs script:
Make sure to apply the suggestions from my previous response, like increasing the batch size and buffer size, and see how the changes affect the learning process. Experiment with different reward signals and positions to create a more diverse learning experience for the agent.
Here's how you can use the Ray Perception Sensor 2D component in your project:
First, select your Player (Agent) game object in the Unity Inspector.
Click on "Add Component" at the bottom of the Inspector window.
Search for "Ray Perception Sensor 2D" in the search bar and click on it to add the component to your agent.
Customize the Ray Perception Sensor 2D component's settings:
Ray Distance: The length of the rays cast in the specified directions.
Ray Directions: The number of rays cast in equal angles around the agent. It will determine the angles at which the rays are cast around the agent. For example, if you want to cast rays in four directions (up, down, left, right), you can provide a list with angles [0, 90, 180, 270].
Detectable Tags: A list of GameObject tags that the sensor can detect. Make sure the objects you want to detect have these tags assigned.
Transform: A reference to the agent's Transform component (automatically assigned when you add the component).
Sensor Name: A custom name for the sensor, which can be useful when you have multiple Ray Perception Sensor components on the same agent.
Update your PlayerController.cs script to incorporate the raycast observations. Remove the part where you collect the food positions inside CollectObservations:
public override void CollectObservations(VectorSensor sensor)
{
sensor.AddObservation(rb.velocity.x);
sensor.AddObservation(rb.velocity.y);
}
With the Ray Perception Sensor 2D component added to the agent, the CollectObservations method in your PlayerController.cs script will automatically include the raycast observations.
Make sure the objects you want to detect with the raycasts have the appropriate tags assigned in the Inspector. For example, if you want to detect food, give the food GameObject a "Food" tag and add it to the Detectable Tags list in the Ray Perception Sensor 2D component.
Now, the agent will use the rays to detect objects around it, and these observations will be included in the learning process. This information can be helpful for the agent to navigate around its environment, especially when positional data of objects is not provided explicitly.
i have an PlayerController.cs code. I already created and set up ray perception sensor 2d in agent's inspector. But i have 0 observations during training. how to fix it:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Sensors.Reflection;
[AddComponentMenu("")]
public class PlayerController : Agent
{
public float speed = 5f;
private Rigidbody2D rb;
private FoodSpawner foodSpawner;
private Vector3 initialPosition;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
initialPosition = transform.position;
}
void Update()
{
ManageEpisode();
}
private void ManageEpisode()
{
SharedAcademy.EpisodeTimeout -= Time.deltaTime;
int remainingFoodCount = foodSpawner.GetComponentsInChildren<Food>().Length;
if (SharedAcademy.EpisodeTimeout <= 0 || remainingFoodCount == 0)
{
ResetPlayerEpisode();
foodSpawner.SpawnFood();
SharedAcademy.EpisodeTimeout = 30f;
}
}
public override void OnEpisodeBegin()
{
rb.velocity = Vector2.zero;
// Get Training Area position
Vector3 trainingAreaPosition = foodSpawner.transform.position;
// Calculate the random position relative to the Training Area
float randomX = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.x;
float randomY = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.y;
initialPosition = new Vector3(randomX, randomY, 0);
transform.position = initialPosition;
}
public override void CollectObservations(VectorSensor sensor)
{
// The observations from ray-based sensor will be automatically collected
}
public override void OnActionReceived(ActionBuffers actions)
{
float moveHorizontal = actions.ContinuousActions[0];
float moveVertical = actions.ContinuousActions[1];
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb.AddForce(movement * speed);
float minDistance = float.MaxValue;
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
float distance = Vector2.Distance(transform.position, food.transform.position);
if (distance < minDistance)
{
minDistance = distance;
}
}
// Add a penalty proportional to the distance to the nearest food.
SetReward(-minDistance * Time.fixedDeltaTime);
}
public void AddRewardOnEatingFood()
{
AddReward(1f);
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var continuousActionsOut = actionsOut.ContinuousActions;
continuousActionsOut[0] = Input.GetAxis("Horizontal");
continuousActionsOut[1] = Input.GetAxis("Vertical");
}
public void ResetPlayerEpisode()
{
EndEpisode();
transform.position = initialPosition; // Reset player position to the initial position
rb.velocity = Vector2.zero;
}
public void SetFoodSpawner(FoodSpawner spawner)
{
foodSpawner = spawner;
}
}
CollectObservations
Here's how to add Ray Perception Sensor observations in CollectObservations for ML-Agents versions before 1.0.0.
First, you need a reference to the Ray Perception Sensor 2D component in the PlayerController.cs script (assuming that you already added the Ray Perception Sensor 2D component to the agent via the Inspector).
Add a new public field to the PlayerController.cs script:
public RayPerceptionSensorComponent2D rayPerception;
Link the Ray Perception Sensor component to the new rayPerception field in the Unity Inspector.
Modify the CollectObservations method to include ray perception observations using the rayPerception.Perceive method.
public override void CollectObservations(VectorSensor sensor)
{
if (rayPerception != null)
{
var rayObservations = rayPerception.Perceive(rayPerception.rayLength, rayPerception.rayAngles, rayPerception.detectableTags, rayPerception.startOffset, rayPerception.endOffset);
sensor.AddObservation(rayObservations);
}
}
Ensure that the detectable tags you want the agent to perceive are added to the Ray Perception Sensor 2D component's "Detectable Tags" property in the Inspector. Make sure the objects (for example, Food) that you want the agent to detect have the correct tags. If you add or remove elements in the "Detectable Tags", update the obsSize according to the number of tags used to ensure smooth training.
These steps apply to ML-Agents version 0.15.x or lower. If you still face issues, please make sure that you are running a compatible version of ML-Agents and confirm that your Ray Perception Sensor setup is correct.
Assets\Scripts\PlayerController.cs(63,152): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'startOffset' and no accessible extension method 'startOffset' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\PlayerController.cs(63,179): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'endOffset' and no accessible extension method 'endOffset' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\PlayerController.cs(63,49): error CS1061: 'RayPerceptionSensorComponent2D' does not contain a definition for 'Perceive' and no accessible extension method 'Perceive' accepting a first argument of type 'RayPerceptionSensorComponent2D' could be found (are you missing a using directive or an assembly reference?)
Also, double-check that your agent's behavior name (for example, "PlayerLearning") is correctly added to the MLAgentsOverride.yaml and the YAML configuration for your training matches the agent setup.
The Ray Perception Sensor component will collect observations for the agent automatically without adjusting the script in newer versions of ML-Agents. The observations will be used during the training process, and you should see your agent reacting to nearby objects according to the learned policy.
Look for a dropdown list called "Observations". This list should show you the observations from your agent.
If you still don't see any observations, it might be possible that the Ray Perception Sensor 2D is not registered to the Agent properly.
To further debug this issue, go to the ML-Agents GitHub repository and check their example scenes to see if you are following the same configuration settings. You can find the example scenes in the following path: Assets > ML-Agents > Examples.
To resolve this issue, you can manually collect the observations of the Ray Perception Sensor 2D in the CollectObservations method and feed them into the vector sensor:
Update your PlayerController script to access the Ray Perception Sensor 2D by adding a reference:
Make sure to assign the correct reference to the rayPerception field in the Unity Inspector.
Modify the CollectObservations method to include the raycast observations:
public override void CollectObservations(VectorSensor sensor)
{
if (rayPerception != null)
{
var raySensor = rayPerception.GetComponent<RayPerceptionSensorComponent2D>();
var perceptionBufferSensor = GetComponent<PerceptionSensorComponent2D>();
if (raySensor != null && perceptionBufferSensor != null)
{
var raycastObservations = raySensor.CreateSensor().GetObservations();
foreach (var observation in raycastObservations)
{
sensor.AddObservation(observation);
}
}
}
}
By adding these changes to your CollectObservations method, the Ray Perception Sensor 2D observations are explicitly sent to the Agent, and the error should not appear in the Unity Console.
With these modifications, the Agent should learn using the Ray Perception Sensor 2D data without issues. Please remember that, in general, running the training environment in play mode inside Unity is NOT recommended when training ML Agents, but it can be useful for initial debugging purposes.