Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Unity AI help

Discussion in 'Getting Started' started by d3vr1es, Mar 25, 2023.

  1. d3vr1es

    d3vr1es

    Joined:
    Mar 23, 2023
    Posts:
    2
    Question: Where do I attach my c# scripts within unity to the agents I have images attached this would be for meadowarea, farmer, each animal and food item.

    I need help getting this to work, attached is my unity project images , and the required c# scripts that I have. I am working with unity to create a farmlife simulator where I have a farmeragent who wonders around the meadow and feeds animalagents, pig, cow, chicken. truffles, apple, corn according to the prefered food of each animal. your welcome to take a look at the code and let me know if im going in the right direction. I am new to this so still learning. I have the 4 agents and the objects within Unity setup looking to get to do actuall training if everything looks good.
    Code (CSharp):
    1.  
    2. MeadowArea.cs
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6. using MLAgents;
    7. using TMPro;
    8.  
    9. public class MeadowArea : Area
    10. {
    11.     public FarmerAgent FarmerAgent;
    12.     public TextMeshPro cumulativeRewardText;
    13.  
    14.     [HideInInspector]
    15.     public float feedRadius = 1f;
    16.  
    17.     private List<GameObject> areaList;
    18.  
    19.     public override void ResetArea()
    20.     {
    21.         RemoveAllFoodItems();
    22.         PlaceCow();
    23.         PlaceChicken();
    24.         PlacePig();
    25.         PlaceFarmer();
    26.         SpawnTree(4);
    27.         SpawnStump(3);
    28.     }
    29.  
    30.     public void RemoveSpecificFoodItem(GameObject foodItemObject)
    31.     {
    32.         areaList.Remove(foodItemObject);
    33.         Destroy(foodItemObject);
    34.     }
    35.  
    36.     public static Vector3 ChooseRandomPosition(Vector3 center, float minAngle, float maxAngle, float minRadius, float maxRadius)
    37.     {
    38.         float radius = minRadius;
    39.         if (maxRadius > minRadius)
    40.         {
    41.             radius = UnityEngine.Random.Range(minRadius, maxRadius);
    42.         }
    43.         return center + Quaternion.Euler(0f, UnityEngine.Random.Range(minAngle, maxAngle), 0f) * Vector3.forward * radius;
    44.     }
    45.  
    46.     private void RemoveAllFoodItems()
    47.     {
    48.         if (areaList != null)
    49.         {
    50.             for (int i = 0; i < areaList.Count; i++)
    51.             {
    52.                 if (areaList[i] != null)
    53.                 {
    54.                     Destroy(areaList[i]);
    55.                 }
    56.             }
    57.         }
    58.         areaList = new List<GameObject>();
    59.     }
    60.  
    61.     private void PlaceCow()
    62.     {
    63.         Vector3 position = ChooseRandomPosition(transform.position, -180f, 180f, 1f, 8f);
    64.         Instantiate(FarmerAgent.horse, position, Quaternion.Euler(0f, UnityEngine.Random.Range(-180f, 180f), 0f), transform);
    65.     }
    66.  
    67.     private void PlaceChicken()
    68.     {
    69.         Vector3 position = ChooseRandomPosition(transform.position, -180f, 180f, 1f, 8f);
    70.         Instantiate(FarmerAgent.chicken, position, Quaternion.Euler(0f, UnityEngine.Random.Range(-180f, 180f), 0f), transform);
    71.     }
    72.  
    73.     private void PlacePig()
    74. {
    75. Vector3 position = ChooseRandomPosition(transform.position, -Mathf.PI / 4f, Mathf.PI / 4f, 0f, 4f);
    76. GameObject pigObject = Instantiate(pig, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f));
    77. pigObject.GetComponent<AnimalAgent>().preferredFood = Food.Truffle;
    78. areaList.Add(pigObject);
    79. }
    80.  
    81. private void PlaceFarmer()
    82. {
    83. Vector3 position = ChooseRandomPosition(transform.position, -Mathf.PI / 4f, Mathf.PI / 4f, 0f, 4f);
    84. GameObject farmerObject = Instantiate(FarmerAgent.gameObject, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f));
    85. areaList.Add(farmerObject);
    86. }
    87.  
    88. private void SpawnTree(int treeCount)
    89. {
    90. for (int i = 0; i < treeCount; i++)
    91. {
    92. Vector3 position = ChooseRandomPosition(transform.position, -Mathf.PI / 4f, Mathf.PI / 4f, 3f, 9f);
    93. GameObject treeObject = Instantiate(FoodItem.Tree.gameObject, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f));
    94. areaList.Add(treeObject);
    95. }
    96. }
    97.  
    98. private void SpawnStump(int stumpCount)
    99. {
    100. for (int i = 0; i < stumpCount; i++)
    101. {
    102. Vector3 position = ChooseRandomPosition(transform.position, -Mathf.PI / 4f, Mathf.PI / 4f, 3f, 9f);
    103. GameObject stumpObject = Instantiate(FoodItem.Stump.gameObject, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f));
    104. areaList.Add(stumpObject);
    105. }
    106. }
    107. Farmeragent.cs
    108. [code=CSharp]using System.Collections;
    109. using System.Collections.Generic;
    110. using UnityEngine;
    111. using Unity.MLAgents;
    112. using Unity.MLAgents.Sensors;
    113.  
    114. public class FarmerAgent : Agent
    115. {
    116.     public GameObject cow;
    117.     public GameObject pig;
    118.     public GameObject chicken;
    119.     public float moveSpeed = 3.5f;
    120.     public float rotationSpeed = 150.0f;
    121.     public float rayDistance = 10.0f;
    122.  
    123.     private bool isCowFed = false;
    124.     private bool isPigFed = false;
    125.     private bool isChickenFed = false;
    126.     private Rigidbody agentRb;
    127.     private RayPerception rayPer;
    128.     private Collider agentCollider;
    129.  
    130.     public override void Initialize()
    131.     {
    132.         agentRb = GetComponent<Rigidbody>();
    133.         rayPer = GetComponent<RayPerception>();
    134.         agentCollider = GetComponent<Collider>();
    135.     }
    136.  
    137.     public override void OnEpisodeBegin()
    138.     {
    139.         isCowFed = false;
    140.         isPigFed = false;
    141.         isChickenFed = false;
    142.     }
    143.  
    144.     public override void CollectObservations(VectorSensor sensor)
    145.     {
    146.         // Detect the closest animal agent
    147.         float[] rayAngles = {0.0f, 45.0f, 90.0f, 135.0f, 180.0f, 225.0f, 270.0f, 315.0f};
    148.         string[] detectableObjects = {"cow", "pig", "chicken"};
    149.  
    150.         sensor.AddObservation(rayPer.Perceive(rayDistance, rayAngles, detectableObjects, 0.0f, 0.0f));
    151.     }
    152.  
    153.     public override void OnActionReceived(float[] vectorAction)
    154.     {
    155.         float horizontal = vectorAction[0];
    156.         float vertical = vectorAction[1];
    157.  
    158.         // Move the agent
    159.         agentRb.velocity = transform.forward * vertical * moveSpeed;
    160.         transform.Rotate(Vector3.up, horizontal * rotationSpeed * Time.deltaTime);
    161.  
    162.         // Drop the appropriate food based on the closest animal agent
    163.         RaycastHit hit;
    164.         if (Physics.Raycast(transform.position, transform.forward, out hit, rayDistance))
    165.         {
    166.             if (hit.collider.CompareTag("cow") && !isCowFed)
    167.             {
    168.                 DropApple(cow);
    169.             }
    170.             else if (hit.collider.CompareTag("pig") && !isPigFed)
    171.             {
    172.                 DropTruffle(pig);
    173.             }
    174.             else if (hit.collider.CompareTag("chicken") && !isChickenFed)
    175.             {
    176.                 DropCorn(chicken);
    177.             }
    178.         }
    179.  
    180.         // Penalize the agent for moving into walls or outside of the meadow
    181.         if (transform.position.magnitude > 8.5f)
    182.         {
    183.             AddReward(-1.0f);
    184.             EndEpisode();
    185.         }
    186.  
    187.         // Turn the agent if it runs into a tree or stump
    188.         if (Physics.Raycast(transform.position, transform.forward, out hit, agentCollider.bounds.extents.z))
    189.         {
    190.             if (hit.collider.CompareTag("Tree") || hit.collider.CompareTag("Stump"))
    191.             {
    192.                 transform.Rotate(Vector3.up, 180.0f);
    193.             }
    194.         }
    195.     }
    196.  
    197.     private void DropApple(GameObject animal)
    198.     {
    199.         if (animal.GetComponent<AnimalAgent>().preferredFood == Food.Apple)
    200.         {
    201.             animal.GetComponent<AnimalAgent>().isFed = true;
    202.             isCowFed = true;
    203.             AddReward(1.0f);
    204.         }
    205.         else
    206.         {
    207.             AddReward(-1.0f);
    208.         }
    209.     }
    210.  
    211.    private void DropTruffle(GameObject animal)
    212.     {
    213.         if (animal.GetComponent<AnimalAgent>().preferredFood == Food.Truffle)
    214.         {
    215.             animal.GetComponent<AnimalAgent>().isFed = true;
    216.             isPigFed = true;
    217.             AddReward(1.0f);
    218.         }
    219.         else
    220.         {
    221.             AddReward(-1.0f);
    222.         }
    223.     }private void DropCorn(GameObject animal)
    224.     {
    225.         if (animal.GetComponent<AnimalAgent>().preferredFood == Food.Corn)
    226.         {
    227.             animal.GetComponent<AnimalAgent>().isFed = true;
    228.             isChickenFed = true;
    229.             AddReward(1.0f);
    230.         }
    231.         else
    232.         {
    233.             AddReward(-1.0f);
    234.         }
    235.     }
    236. }
    AnimalAgent.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.MLAgents;
    5. using Unity.MLAgents.Sensors;
    6.  
    7. public class AnimalAgent : Agent
    8. {
    9.     public Food preferredFood;
    10.     public float moveSpeed;
    11.     public float rotationSpeed;
    12.     public float rayDistance;
    13.     public LayerMask rayLayerMask;
    14.  
    15.     private Rigidbody rb;
    16.  
    17.     public override void Initialize()
    18.     {
    19.         rb = GetComponent<Rigidbody>();
    20.     }
    21.  
    22.     public override void OnEpisodeBegin()
    23.     {
    24.         rb.velocity = Vector3.zero;
    25.         rb.angularVelocity = Vector3.zero;
    26.     }
    27.  
    28.     public override void CollectObservations(VectorSensor sensor)
    29.     {
    30.         // Ray perception to detect closest food item
    31.         float[] rayAngles = {0f, 45f, 90f, 135f, 180f, 225f, 270f, 315f};
    32.         string[] detectableObjects = { "Food" };
    33.         sensor.AddObservation(GetComponent<RayPerceptionSensorComponent3D>().Perceive(rayDistance, rayAngles, detectableObjects, 0f, 0f));
    34.     }
    35.  
    36.     public override void OnActionReceived(float[] vectorAction)
    37.     {
    38.         float forwardInput = Mathf.Clamp(vectorAction[0], -1f, 1f);
    39.         float rotationInput = Mathf.Clamp(vectorAction[1], -1f, 1f);
    40.  
    41.         // Move the animal
    42.         Vector3 movement = transform.forward * forwardInput * moveSpeed * Time.deltaTime;
    43.         rb.MovePosition(rb.position + movement);
    44.  
    45.         // Rotate the animal
    46.         float rotation = rotationInput * rotationSpeed * Time.deltaTime;
    47.         Quaternion turnRotation = Quaternion.Euler(0f, rotation, 0f);
    48.         rb.MoveRotation(rb.rotation * turnRotation);
    49.     }
    50.  
    51.     private void OnTriggerEnter(Collider other)
    52.     {
    53.         if (other.CompareTag("Food"))
    54.         {
    55.             FoodItem foodItem = other.GetComponent<FoodItem>();
    56.             if (foodItem.foodType == preferredFood)
    57.             {
    58.                 AddReward(1.0f);
    59.                 Destroy(other.gameObject);
    60.                 EndEpisode();
    61.             }
    62.             else
    63.             {
    64.                 AddReward(-0.1f);
    65.             }
    66.         }
    67.         else if (other.CompareTag("Wall") || other.CompareTag("Environment"))
    68.         {
    69.             AddReward(-0.1f);
    70.         }
    71.     }
    72. }
    73.  
    FoodItem.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.MLAgents;
    5.  
    6. public class FoodItem : MonoBehaviour
    7. {
    8.     public Food foodType;
    9. }
    }
    this is zoomed so you can see the 3 blobs that will be the food, they are different colors to help the AI figure out which is for each animal orange is the apple, yellow is the corn, black is truffle.

    what I need help with is the prefab agent trees under the inspector tab i'm trying to set the brains up for training. But cannot figure it out.



    Where do I attach my scripts?