I have copied my TrainingArea many times, and while training, it seems to me that when other agents eat their food, it disappears from the first agent. I may be wrong and it may not be. But I know for sure that the food disappears by itself from the very first agent.
here's my TrainingArea.cs:
using UnityEngine;
using System.Collections.Generic;
public class TrainingArea : MonoBehaviour
{
[SerializeField] private GameObject playerPrefab;
[SerializeField] private GameObject foodPrefab;
[SerializeField] private int numberOfFoods = 10;
[SerializeField] private float spawnRadius = 5.0f;
private PlayerAgent playerAgent;
private List foodInstances = new List();
private void Start()
{
SpawnPlayer();
SpawnFoods();
}
public void ResetArea()
{
ResetPlayer();
ResetFoods();
}
private void ResetPlayer()
{
if (playerAgent != null)
{
playerAgent.transform.localPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
}
}
public void ResetFoods()
{
List<GameObject> eatenFoods = new List<GameObject>();
foreach (GameObject food in foodInstances)
{
if (food != null)
{
food.transform.localPosition = GetValidSpawnPosition();
}
else
{
eatenFoods.Add(food);
}
}
foreach (GameObject food in eatenFoods)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstances.Add(foodInstance);
}
// Remove eaten food references from the list
foodInstances.RemoveAll(food => food == null);
}
private void SpawnPlayer()
{
Vector3 randomPosition = GetValidSpawnPosition();
GameObject playerInstance = Instantiate(playerPrefab, randomPosition + transform.position, Quaternion.identity, transform);
playerAgent = playerInstance.GetComponent<PlayerAgent>();
}
private void SpawnFoods()
{
for (int i = 0; i < numberOfFoods; i++)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstances.Add(foodInstance);
}
}
private Vector3 GetValidSpawnPosition()
{
Vector3 spawnPosition;
do
{
spawnPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
} while (playerAgent != null && Vector3.Distance(playerAgent.transform.localPosition, spawnPosition) <= 5.0f);
return spawnPosition;
}
public bool AllFoodEaten()
{
foreach (GameObject food in foodInstances)
{
if (food != null)
{
return false;
}
}
return true;
}
}
here's my PlayerAgent.cs:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
It seems like the food disappearing from the first agent might be caused by the ResetFoods() method in your TrainingArea script. When a food object is destroyed by one agent, it's set to null in the foodInstances list (like you mentioned), which later causes it to be recreated at a different spawn position when the method is called.
I recommend using a different approach to handle the food, without having to destroy and instantiate the food GameObjects again.
Remove the Destroy(collider2.gameObject); line from the OnActionReceived method in the PlayerAgent script.
Add the following method to the TrainingArea script:
public void EatFood(GameObject food)
{
// Set food to an inaccessible position, rather than destroying it
food.transform.position = Vector3.one * 9999;
}
User
The problem is that if a player from the second TrainingArea goes to the same corner that has food in the first TrainingArea, then the food will disappear in the first TrainingArea.
Assistant
Your understanding is correct. The issue is that the food objects are spawned with the global world position, which might cause interference between different training areas. To fix this, change all positions to be local to each TrainingArea.
In the TrainingArea script, replace the line in the SpawnFoods() method:
This will ensure that the food object is moved far away within the local space of the TrainingArea and prevents interference between different instances.
User
Assistant
I understand the issue you're experiencing. Since the food objects are moved far away from the center of the TrainingArea using local coordinates, their actual position in the world space might still interfere with other agents. To fix this, you can move the food objects out of reach specifically in the transform hierarchy of their respective TrainingArea.
Modify the EatFood() function in the TrainingArea script as follows:
public void EatFood(GameObject food)
{
// Move the food object far away and parent it to the TrainingArea.
food.transform.parent = transform;
food.transform.localPosition = Vector3.one * 9999;
}
User
you did not understand me. even if there is only one TrainingArea left on the stage, and if I move it to the right, my food will be considered eaten if it is far to the right. The same for the left, the more I move the TrainingArea to the left, the more it will be on the left, even if the sprites are displayed correctly. The same goes for top and bottom. The ideal position of the TrainingArea is 0,0,0 where everything works correctly. Fix it.
Assistant
I apologize for the confusion. I understand the issue now. The problem is that the eating mechanism is checking for a fixed world distance. When the TrainingArea is moved or rotated, the actual positions of the foods changes.
To fix this issue, we can store the initial world position of the TrainingArea in a variable and use it to handle the food check.
Add a new variable in the TrainingArea script:
private Vector3 initialPosition;
In the Start() method, add the following line to store the initial position of the TrainingArea:
initialPosition = transform.position;
Modify the GetValidSpawnPosition() method to return world coordinates by adding the to the spawn position:
User
Assistant
The issue occurs because, in the ResetFoods() method, you're calculating the spawn position using local coordinates but calling Instantiate() with world coordinates. You should convert the spawn position to world coordinates for each food object when creating them.
Modify the line inside the foreach loop in the ResetFoods() method:
Assign the Ray Perception Sensor 2D component in the Editor inspector to the newly created field.
In the Update method of the PlayerAgent script, add the following code to draw the sensor rays in the scene:
private void Update()
{
if (rayPerception != null)
{
List<float> rayObservations = rayPerception.Perceive(rayPerception.Sensor.Perceive());
RaycastHit2D hit;
for (int i = 0; i < rayPerception.RayAngles.Length; i++)
{
float angle = rayPerception.RayAngles[i] + transform.eulerAngles.z;
Vector3 direction = Quaternion.Euler(0, 0, angle) * Vector2.right;
hit = Physics2D.Raycast(transform.position, direction, rayPerception.RayDistance, LayerMask.GetMask("Wall", "Food"));
Debug.DrawLine(transform.position, transform.position + direction * hit.distance, Color.red);
}
}
}
User
Assistant
To collect the positions of the player and the remaining food objects in their respective TrainingArea as observations, you can modify the CollectObservations() method in the PlayerAgent script.
First, you need to convert the food and player positions to local coordinates relative to their TrainingArea. You can create a helper method in the TrainingArea script to achieve this:
public Vector3 WorldToLocalCoordinates(Vector3 worldCoordinates)
{
return transform.InverseTransformPoint(worldCoordinates);
}
Now, in the PlayerAgent script, update the CollectObservations() method as follows:
public override void CollectObservations(VectorSensor sensor)
{
// Get the player's local position in the TrainingArea
Vector3 localPlayerPosition = trainingArea.WorldToLocalCoordinates(transform.position);
sensor.AddObservation(localPlayerPosition);
// Add observations for the food objects
foreach (GameObject food in trainingArea.GetFoodInstances())
{
if (food != null)
{
// Only add the local position of the remaining (not eaten) food objects
Vector3 localFoodPosition = trainingArea.WorldToLocalCoordinates(food.transform.position);
sensor.AddObservation(localFoodPosition);
}
}
}
User
my neural network quickly plateaus without starting to understand how to play. I even set -reward when it hits a wall. I don’t understand what the problem is, help me assign rewards.
public override void OnActionReceived(ActionBuffers actions)
{
float moveX = Mathf.Clamp(actions.ContinuousActions[0], -1, 1);
float moveY = Mathf.Clamp(actions.ContinuousActions[1], -1, 1);
Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime;
Vector3 newPosition = transform.position + move; // Change to position instead of localPosition
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Wall"));
if (collider == null || !collider.CompareTag("Wall"))
{
SetReward(-0.1f);
transform.position = newPosition; // Change to position instead of localPosition
}
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider2 = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Food"));
if (collider2 != null && collider2.CompareTag("Food"))
{
// Make sure the food object is part of the current TrainingArea
if (trainingArea.GetFoodInstances().Contains(collider2.gameObject))
{
Debug.Log("OnTriggerEnter2D");
SetReward(1f);
Destroy(collider2.gameObject);
}
}
}
Assistant
There are several potential improvements you can make in terms of rewards and observations, which may lead to better performance of your neural network:
User
it's already much better, my agent has started gathering food and being afraid of the walls. but now he is afraid to collect food, which is right next to the walls.
Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime;
Vector3 newPosition = transform.position + move;
Collider2D wallCollider = Physics2D.OverlapCircle(newPosition, 0.5f, LayerMask.GetMask("Wall"));
if (wallCollider != null && wallCollider.CompareTag("Wall"))
{
// Add a minor negative reward when hitting the wall
SetReward(-0.5f);
}
else
{
// Decrease the negative reward
SetReward(-0.01f);
transform.position = newPosition;
}
Collider2D foodCollider = Physics2D.OverlapCircle(newPosition, 0.5f, LayerMask.GetMask("Food"));
if (foodCollider != null && foodCollider.CompareTag("Food"))
{
if (trainingArea.GetFoodInstances().Contains(foodCollider.gameObject))
{
SetReward(1f);
Destroy(foodCollider.gameObject);
// Add bonus reward if all food has been eaten
if (trainingArea.AllFoodEaten())
{
SetReward(5f);
}
}
}
}
Assistant
It appears that the negative reward given when the agent collides with a wall is causing the agent to avoid the food near the walls. To address this issue, you can provide the agent with more precise control of its movement by introducing turning and forward actions instead of directly controlling horizontal and vertical movement. This way, the agent can better navigate around the wall edges to collect the food.
Here's an updated version of the OnActionReceived method for turning and forward movement:
This method will move the food object far away from the training area, effectively making it inaccessible for the agents, without Destroying or Reinstantiating it.
In the PlayerAgent script, replace the Destroy(collider2.gameObject); line with:
trainingArea.EatFood(collider2.gameObject);
Finally, to fix the food disappearing when a new episode starts, modify the foreach loop in the ResetFoods() method in the TrainingArea script like this:
foreach (GameObject food in foodInstances)
{
food.transform.localPosition = GetValidSpawnPosition();
}
By doing this, you're reusing the same food instances without destroying or creating new ones, which should resolve the issue of food disappearing from the first agent while training.
With these changes, food objects in different TrainingArea instances should not interfere with each other, ensuring that the food does not disappear unexpectedly.
Great, now players from other TrainingAreas can't eat food from the first TrainingArea. The problem remains that they cannot eat food from their TrainingArea because the food sprites are correctly positioned, but their actual location is far to the right, relative to the center of the TrainingArea .
TrainingArea.cs:
using UnityEngine;
using System.Collections.Generic;
public class TrainingArea : MonoBehaviour
{
[HideInInspector] public GameObject playerPrefab;
[HideInInspector] public GameObject foodPrefab;
[SerializeField] private int numberOfFoods = 10;
[SerializeField] private float spawnRadius = 5.0f;
private PlayerAgent playerAgent;
private List foodInstances = new List();
private void Start()
{
SpawnPlayer();
SpawnFoods();
}
public void ResetArea()
{
ResetPlayer();
ResetFoods();
}
private void ResetPlayer()
{
if (playerAgent != null)
{
playerAgent.transform.localPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
}
}
public void ResetFoods()
{
List<GameObject> eatenFoods = new List<GameObject>();
foreach (GameObject food in foodInstances)
{
if (food != null)
{
food.transform.localPosition = GetValidSpawnPosition();
}
else
{
eatenFoods.Add(food);
}
}
foreach (GameObject food in eatenFoods)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstance.layer = LayerMask.NameToLayer("Food");
foodInstances.Add(foodInstance);
}
// Remove eaten food references from the list
foodInstances.RemoveAll(food => food == null);
}
private void SpawnPlayer()
{
Vector3 randomPosition = GetValidSpawnPosition();
GameObject playerInstance = Instantiate(playerPrefab, randomPosition + transform.position, Quaternion.identity, transform);
playerInstance.layer = LayerMask.NameToLayer("Player");
playerAgent = playerInstance.GetComponent<PlayerAgent>();
}
private void SpawnFoods()
{
for (int i = 0; i < numberOfFoods; i++)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstance.layer = LayerMask.NameToLayer("Food");
foodInstances.Add(foodInstance);
}
}
private Vector3 GetValidSpawnPosition()
{
Vector3 spawnPosition;
do
{
spawnPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
} while (playerAgent != null && Vector3.Distance(playerAgent.transform.localPosition, spawnPosition) <= 5.0f);
return spawnPosition;
}
public bool AllFoodEaten()
{
foreach (GameObject food in foodInstances)
{
if (food != null)
{
return false;
}
}
return true;
}
public List <GameObject> GetFoodInstances()
{
return foodInstances;
}
}
This change will ensure that the food objects are moved out of reach within the local space of their TrainingArea in the transform hierarchy, and other agents should not be able to eat food from their respective TrainingArea.
If this method is still having issues, another approach is to use a boolean flag to check if the food object is eaten in the PlayerAgent script.
Create a new script named Food.cs and add the following code:
using UnityEngine;
public class Food : MonoBehaviour
{
public bool isEaten = false;
}
Attach this script to the food Prefab.
Now add a reference of it in your PlayerAgent script. Replace the following line in the OnActionReceived method:
trainingArea.EatFood(collider2.gameObject);
with:
collider2.GetComponent<Food>().isEaten = true;
Finally, modify the condition inside the AllFoodEaten() method in the TrainingArea script:
public bool AllFoodEaten()
{
foreach (GameObject food in foodInstances)
{
if (!food.GetComponent<Food>().isEaten)
{
return false;
}
}
return true;
}
By using this method, you are checking if the food is eaten without changing its position. This should resolve the issue you are experiencing.
Now, modify the EatFood() method to look like this:
public void EatFood(GameObject food)
{
// Move the food object far away and parent it to the TrainingArea.
food.transform.parent = transform;
food.transform.position = Vector3.one * 9999;
}
By making these changes, the TrainingArea should work correctly regardless of its position in the world space, and the issue of food not being eaten should be resolved.
Now the food is eating normally. But the problem is that when all the food is eaten, a new episode starts, and the food appears in the very first TrainingArea, instead of its own.
here's my TrainingArea.cs:
using UnityEngine;
using System.Collections.Generic;
public class TrainingArea : MonoBehaviour
{
[HideInInspector] public GameObject playerPrefab;
[HideInInspector] public GameObject foodPrefab;
[SerializeField] private int numberOfFoods = 10;
[SerializeField] private float spawnRadius = 5.0f;
private PlayerAgent playerAgent;
private List foodInstances = new List();
private void Start()
{
SpawnPlayer();
SpawnFoods();
}
public void ResetArea()
{
ResetPlayer();
ResetFoods();
}
private void ResetPlayer()
{
if (playerAgent != null)
{
playerAgent.transform.localPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
}
}
public void ResetFoods()
{
List<GameObject> eatenFoods = new List<GameObject>();
foreach (GameObject food in foodInstances)
{
if (food != null)
{
food.transform.localPosition = GetValidSpawnPosition();
}
else
{
eatenFoods.Add(food);
}
}
foreach (GameObject food in eatenFoods)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstance.layer = LayerMask.NameToLayer("Food");
foodInstances.Add(foodInstance);
}
// Remove eaten food references from the list
foodInstances.RemoveAll(food => food == null);
}
private void SpawnPlayer()
{
Vector3 randomPosition = GetValidSpawnPosition();
GameObject playerInstance = Instantiate(playerPrefab, randomPosition + transform.position, Quaternion.identity, transform);
playerInstance.layer = LayerMask.NameToLayer("Player");
playerAgent = playerInstance.GetComponent<PlayerAgent>();
}
private void SpawnFoods()
{
for (int i = 0; i < numberOfFoods; i++)
{
Vector3 spawnPosition = GetValidSpawnPosition();
GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
foodInstance.layer = LayerMask.NameToLayer("Food");
foodInstances.Add(foodInstance);
}
}
private Vector3 GetValidSpawnPosition()
{
Vector3 spawnPosition;
do
{
spawnPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0);
} while (playerAgent != null && Vector3.Distance(playerAgent.transform.localPosition, spawnPosition) <= 5.0f);
return spawnPosition;
}
public bool AllFoodEaten()
{
foreach (GameObject food in foodInstances)
{
if (food != null)
{
return false;
}
}
return true;
}
public List <GameObject> GetFoodInstances()
{
return foodInstances;
}
}
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
public override void Initialize()
{
trainingArea = GetComponentInParent<TrainingArea>();
}
public override void OnEpisodeBegin()
{
trainingArea.ResetArea();
episodeTime = 0.0f;
}
public override void CollectObservations(VectorSensor sensor)
{
sensor.AddObservation(transform.localPosition);
}
public override void OnActionReceived(ActionBuffers actions)
{
float moveX = Mathf.Clamp(actions.ContinuousActions[0], -1, 1);
float moveY = Mathf.Clamp(actions.ContinuousActions[1], -1, 1);
Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime;
Vector3 newPosition = transform.position + move; // Change to position instead of localPosition
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Wall"));
if (collider == null || !collider.CompareTag("Wall"))
{
SetReward(-0.1f);
transform.position = newPosition; // Change to position instead of localPosition
}
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider2 = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Food"));
if (collider2 != null && collider2.CompareTag("Food"))
{
// Make sure the food object is part of the current TrainingArea
if (trainingArea.GetFoodInstances().Contains(collider2.gameObject))
{
Debug.Log("OnTriggerEnter2D");
SetReward(1f);
Destroy(collider2.gameObject);
}
}
}
public override void Heuristic(in ActionBuffers actionsOut)
{
ActionSegment<float> continuousActions = actionsOut.ContinuousActions;
continuousActions[0] = Input.GetAxis("Horizontal");
continuousActions[1] = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
episodeTime += Time.fixedDeltaTime;
if (episodeTime >= maxEpisodeTime || trainingArea.AllFoodEaten())
{
EndEpisode();
}
}
}
This code will draw red lines for the detected rays of Ray Perception Sensor 2D in the scene view when playing the game. You can see if the sensor is detecting walls and foods correctly.
I have a 2D game, I want to collect the position of the player and food from his TrainingArea as an observation. Food can be eaten and it will disappear, so you will have to account for this in your code so that there are no errors.
Here is PlayerAgent.cs:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
public override void Initialize()
{
trainingArea = GetComponentInParent<TrainingArea>();
}
public override void OnEpisodeBegin()
{
trainingArea.ResetArea();
episodeTime = 0.0f;
}
public override void CollectObservations(VectorSensor sensor)
{
sensor.AddObservation(transform.localPosition);
}
public override void OnActionReceived(ActionBuffers actions)
{
float moveX = Mathf.Clamp(actions.ContinuousActions[0], -1, 1);
float moveY = Mathf.Clamp(actions.ContinuousActions[1], -1, 1);
Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime;
Vector3 newPosition = transform.position + move; // Change to position instead of localPosition
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Wall"));
if (collider == null || !collider.CompareTag("Wall"))
{
SetReward(-0.1f);
transform.position = newPosition; // Change to position instead of localPosition
}
// Change the OverlapCircle to use transform.position (world space) instead of localPosition
Collider2D collider2 = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Food"));
if (collider2 != null && collider2.CompareTag("Food"))
{
// Make sure the food object is part of the current TrainingArea
if (trainingArea.GetFoodInstances().Contains(collider2.gameObject))
{
Debug.Log("OnTriggerEnter2D");
SetReward(1f);
Destroy(collider2.gameObject);
}
}
}
public override void Heuristic(in ActionBuffers actionsOut)
{
ActionSegment<float> continuousActions = actionsOut.ContinuousActions;
continuousActions[0] = Input.GetAxis("Horizontal");
continuousActions[1] = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
episodeTime += Time.fixedDeltaTime;
if (episodeTime >= maxEpisodeTime || trainingArea.AllFoodEaten())
{
EndEpisode();
}
}
}
here's TrainingArea.cs:
using UnityEngine;
using System.Collections.Generic;
public class TrainingArea : MonoBehaviour
{
[HideInInspector] public GameObject playerPrefab;
[HideInInspector] public GameObject foodPrefab;
[SerializeField] private int numberOfFoods = 10;
[SerializeField] private float spawnRadius = 5.0f;
private PlayerAgent playerAgent;
private List foodInstances = new List();
By doing this, you are collecting the positions of the player and the remaining food objects in the TrainingArea as observations, regardless of whether they are eaten or not. This should give the agent all the necessary information about food and player positions for training without causing any errors.
Reducing the negative reward for moving: A -0.1f reward for every move might be too high, making the agent focus on not moving rather than on achieving the goal.
SetReward(-0.01f);
Penalize the agent more for hitting a wall:
if (collider != null && collider.CompareTag("Wall"))
{
SetReward(-0.5f);
return;
}
Add reward based on how close the agent is to the food, encouraging it to move towards the food:
Create a new method in TrainingArea to get the closest food to the player:
Now, in PlayerAgent, add the reward based on the closest food distance in the FixedUpdate() method:
private float previousClosestFoodDistance;
private void FixedUpdate()
{
GameObject closestFood = trainingArea.GetClosestFood();
if (closestFood != null)
{
float currentClosestFoodDistance = Vector3.Distance(transform.position, closestFood.transform.position);
// Give a little reward if the agent is approaching the closest food
if (currentClosestFoodDistance < previousClosestFoodDistance)
{
SetReward(0.1f);
}
previousClosestFoodDistance = currentClosestFoodDistance;
}
episodeTime += Time.fixedDeltaTime;
if (episodeTime >= maxEpisodeTime || trainingArea.AllFoodEaten())
{
EndEpisode();
}
}
These changes should encourage the agent to actively move towards the food and avoid walls. Make sure to adjust the reward values depending on the requirements of your specific environment. You might also consider adding a larger reward for consuming all food to encourage faster completion of the task.
Another improvement would be to use the Ray Perception Sensor to observe the food positions as well as walls. This should help the agent generalize more and have better performance. If you haven't done so already, set up the_ray_perception_sensor_2d component with Food and Wall detection in Agent's GameObject.