Search code examples
c#unity-game-enginereinforcement-learningml-agent

Switiching to ML Agent script from another script in Unity


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?


Solution

  • 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)