유니티 프로젝트의 저장된 주소 입력

cd C:\Users\pc\OneDrive - dyu.ac.kr\바탕 화면\멋사\2.3D
cd MLAgents
conda create -n mlagent python=3.10.11
y
conda activate mlagent
python -m pip install --upgrade pip
git clone --branch release_22 https://github.com/Unity-Technologies/ml-agents.git
패키지 매니저에 ML Agents을 다운로드하고, Samples에서 Install을 한다.

에셋 산하에 ML Agents가 생겼고,씬으로 가면 3D Ball이 여러개가 있다.







cd ml-agents
pip install torch==2.1.1 -f https://download.pytorch.org/whl/torch_stable.html
python -m pip install ./ml-agents-envs
python -m pip install ./ml-agents
mlagents-learn --help







mlagents-learn --force
이전의 mlagents-learn 해서 유니티 로고를 본적이 있으므로 학습한 경험이 있다. 따라서 위와 같이 덮어쓰기 하면 이전의 학습했던 내용들은 사라진다.


10 . 코드를 작성한다
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using UnityEngine;
public class MoveToBallAgent : Agent
{
[SerializeField] Transform targetTransform;
[SerializeField]
Renderer floorMaterial;
[SerializeField]
Material winMaterial;
[SerializeField]
Material loseMaterial;
void Start()
{
}
public override void OnEpisodeBegin()
{// 새로운 에피소드가 들어올 때 시작
transform.localPosition = new Vector3(0, 0.5f, 0);
}
// 관찰한 결과를 받아옴
public override void CollectObservations(VectorSensor sensor)
{
sensor.AddObservation(transform.localPosition); // localPosition을 사용해야 함
sensor.AddObservation(targetTransform.localPosition);
}
public override void OnActionReceived(ActionBuffers actions)
{ // 결정한 내용을 받아옴
float x = actions.ContinuousActions[0];
float y = actions.ContinuousActions[1];
float moveSpeed = 3f;
//agent가 결정한 내용을 토대로 오브젝트를 움직인다.
transform.Translate(new Vector3(x, 0, y) * Time.deltaTime * moveSpeed);
}
public override void Heuristic(in ActionBuffers actionsOut)
{// 장치를 검증하는 용도
ActionSegment<float> continuousAction = actionsOut.ContinuousActions;
// ActionSegment에 continuousActions을 넣어줌
continuousAction[0] = Input.GetAxisRaw("Horizontal");
continuousAction[1] = Input.GetAxisRaw("Vertical");
// 학습은 계속해서 이어지지만, 에피소드 단위로 끊어 학습한다.
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Ball")
{
Debug.Log("Good");
SetReward(1f); // 상점
floorMaterial.material = winMaterial;
EndEpisode(); // 에피소드 종료 후 새로운 에피소드로 시작시킨다.
}
else if (other.tag == "Wall")
{
Debug.Log("Bad");
SetReward(-1f); // 벌점
floorMaterial.material = loseMaterial;
EndEpisode(); // 에피소드 종료 후 새로운 에피소드로 시작시킨다.
}
}
}


Wall과 Ball은 각각 이름에 맞게 태그로 변경한다.
그 다음 인스펙터에 다음을 할당한다.


mlagents-learn --run-id=MoveToBall