英文:
Switiching to ML Agent script from another script in Unity
问题
我想在Unity中训练两个ML代理(使用自我对弈),我希望代理一开始遵循一个路径跟随脚本,直到它检测到敌对玩家(另一个代理)。一旦检测到,路径跟随脚本将被禁用,代理脚本将被启用。这可能吗?如果可以,应该如何实现?
这是我的代码:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
private void Start()
{
agent = FindObjectsOfType<AIAgent>();
//FindObjectsOfType<AIAgent>();
pathFollowerscript = FindObjectOfType<PathFollower1>();
}
if (IsWithinRange)
{
Debug.Log("Detected " + collider.name);
// 对检测到的碰撞器执行一些操作
collider.tag = enemyTag + "Detected";
//Debug.Log(collider.tag);
//Debug.Log(enemyTag);
pathFollowerscript.enabled = false;
foreach (var a in agent)
{
a.enabled = true;
}
}
else
{
collider.tag = enemyTag;
pathFollowerscript.enabled = true;
}
foreach (var a in agent)
{
a.enabled = false;
}
我在FindObjectsOfType
这一行遇到了NullReferenceException异常,可能是因为在游戏开始时没有代理。有人可以帮我解决这个问题吗?
<details>
<summary>英文:</summary>
I want to train 2 ml agents (same script, using self play) in unity. I want the agent to follow a path following script initially until it detects an enemy player(other agent). Once detected, path following script is disabled and agent script is enabled. Is this possible, if so how?
This is the code I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
private void Start()
{
agent = FindObjectsOfType<AIAgent>();
//FindObjectsOfType<AIAgent>();
pathFollowerscript = FindObjectOfType<PathFollower1>();
}
if (IsWithinRange)
{
Debug.Log("Detected " + collider.name);
// Do something with the detected collider
collider.tag = enemyTag + "Detected";
//Debug.Log(collider.tag);
//Debug.Log(enemyTag);
pathFollowerscript.enabled = false;
foreach (var a in agent)
{
a.enabled = true;
}
}
else
{
collider.tag = enemyTag;
pathFollowerscript.enabled = true;
}
foreach (var a in agent)
{
a.enabled = false;
}
}
I am getting a NullReferenceException at the `FindObjectsOfType' line, maybe because there are no agents at the beginning of play. Can somebody help me with this please?
</details>
# 答案1
**得分**: 0
我找到了原因。这是因为代理最初处于非活动状态,FindObjectsOfType 只能在活动组件上工作,除非传递了参数 FindObjectsOfType(inactive: true)。
<details>
<summary>英文:</summary>
I found the reason for this. It's because the agent is initially inactive and FindObjectsOfType only works on active components unless an argument is passed FindObjectsOfType(inactive: true)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论