{"record":{"id":"b9452118644e1cb1","repo":"Unity-Technologies/ml-agents","slug":"there-can-only-be-one-agent-in-the-environment-but","errorCode":null,"errorMessage":"There can only be one Agent in the environment but {n_agents} were detected.","messagePattern":"There can only be one Agent in the environment but (.+?) were detected\\.","errorType":"exception","errorClass":"UnityGymException","httpStatus":null,"severity":"error","filePath":"ml-agents-envs/mlagents_envs/envs/unity_gym_env.py","lineNumber":319,"sourceCode":"\n    def close(self) -> None:\n        \"\"\"Override _close in your subclass to perform any necessary cleanup.\n        Environments will automatically close() themselves when\n        garbage collected or when the program exits.\n        \"\"\"\n        self._env.close()\n\n    def seed(self, seed: Any = None) -> None:\n        \"\"\"Sets the seed for this env's random number generator(s).\n        Currently not implemented.\n        \"\"\"\n        logger.warning(\"Could not seed environment %s\", self.name)\n        return\n\n    @staticmethod\n    def _check_agents(n_agents: int) -> None:\n        if n_agents > 1:\n            raise UnityGymException(\n                f\"There can only be one Agent in the environment but {n_agents} were detected.\"\n            )\n\n    @property\n    def metadata(self):\n        return {\"render_modes\": [\"rgb_array\"]}\n\n    @property\n    def reward_range(self) -> Tuple[float, float]:\n        return -float(\"inf\"), float(\"inf\")\n\n    @property\n    def action_space(self) -> gym.Space:\n        return self._action_space\n\n    @property\n    def observation_space(self):\n        return self._observation_space","sourceCodeStart":301,"sourceCodeEnd":337,"githubUrl":"https://github.com/Unity-Technologies/ml-agents/blob/3ecb446f75d1e7400eb404c562dc005d3164cffc/ml-agents-envs/mlagents_envs/envs/unity_gym_env.py#L301-L337","documentation":"Static UnityGymEnv._check_agents raises UnityGymException when the environment reports more than one Agent in the single behavior. The gym wrapper is strictly single-agent, matching gym's observation/action space contract.","triggerScenarios":"Called from __init__, reset(), and step() with the number of detected agents (len of agent_ids in DecisionSteps/TerminalSteps) greater than 1.","commonSituations":"Unity scene with multiple Agents sharing one Behavior name; population-based or multi-agent training scenes; environment spawns a second Agent mid-episode, so the error fires during step/reset rather than at construction.","solutions":["Ensure exactly one Agent (per behavior) exists in the Unity scene and rebuild.","Remove extra Agents or move them to a separate behavior (which then trips error 50 — so use the raw UnityEnvironment API instead for multi-agent).","Use mlagents-envs UnityEnvironment directly; DecisionSteps supports N agents natively.","If agents spawn dynamically, gate spawning so total count stays at 1."],"exampleFix":"// before\n# Scene: 3 Agents with behavior \"MyBehavior\"\nenv = UnityGymEnv(UnityEnvironment(file_name='multi_agent_app'))\n// after\n# Scene: 1 Agent with behavior \"MyBehavior\"\nenv = UnityGymEnv(UnityEnvironment(file_name='single_agent_app'))\n# or for multi-agent: unity_env = UnityEnvironment(...); use unity_env.get_steps(\"MyBehavior\")","handlingStrategy":"validation","validationCode":"unity_env.reset()\ndecs, _ = unity_env.get_steps(behavior_name)\nif len(decs.agent_id) > 1:\n    raise ValueError(f\"Gym wrapper needs exactly 1 agent, found {len(decs.agent_id)}\")\nenv = UnityGymEnv(unity_env)","typeGuard":"def is_single_agent(steps) -> bool:\n    return len(steps.agent_id) == 1","tryCatchPattern":"try:\n    obs = env.reset()\nexcept UnityGymException:\n    raise RuntimeError(\"Multiple agents detected; use UnityEnvironment API for multi-agent scenes\")","preventionTips":["Guarantee exactly one Agent per behavior in the scene","Re-check agent count after any scene/spawning change","Use DecisionSteps via UnityEnvironment when N agents are required"],"tags":["gym","unity-environment","single-agent"],"backgroundTag":"multi-agent-unsupported","analyzedSha":"3ecb446f75d1e7400eb404c562dc005d3164cffc","analyzedAt":"2026-09-02T16:33:12.832Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T21:17:11.164Z"}