切换到Unity中的ML Agent脚本,从另一个脚本。

huangapple go评论55阅读模式
英文:

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&lt;AIAgent&gt;();
pathFollowerscript = FindObjectOfType&lt;PathFollower1&gt;();

}
if (IsWithinRange)
{
Debug.Log("Detected " + collider.name);
// Do something with the detected collider

collider.tag = enemyTag + &quot;Detected&quot;;
//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&#39; 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&#39;s because the agent is initially inactive and FindObjectsOfType only works on active components unless an argument is passed FindObjectsOfType(inactive: true)

</details>



huangapple
  • 本文由 发表于 2023年2月23日 19:20:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定