- Home /
The question is answered, right answer was accepted
AI spawner problem
Hi, I have a simple "AI spawner" code:
using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; public class SpawnScript : MonoBehaviour { public GameObject botPrefab; GameObject botPref; public string botName; public bool inResp; public bool makeBot; void Start() { } void Update() { if (inResp == true) { makeBot = false; } else if (inResp == false) { makeBot = true; } if (makeBot == true) { botPref = Instantiate(botPrefab, this.transform.position + this.transform.forward, this.transform.rotation); botPref.name = botName; makeBot = false; } } void OnTriggerEnter(Collider other) { GameObject go = other.transform.gameObject; if (go != null) { inResp = true; } else { inResp = false; } } }
This works fine, but when creating a bot, bot transform.position.z always has +1 than transform.position.z spawner. For example, if the spawner's position is x = 500, y = 1, z = 500, when it creates a bot, it creates it at x = 500, y = 1, z = 501. As a result, it always creates several bots until it detects an object within itself (OnTriggerEnter).
How do I tell him to create a bot in himself? Spawner is a cube that is a trigger
Could you post your code like this next time:
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class SpawnScript : $$anonymous$$onoBehaviour
{
public GameObject botPrefab;
GameObject botPref;
public string botName;
public bool inResp;
public bool makeBot;
void Start()
{
}
void Update()
{
if (inResp == true) { makeBot = false; }
else if (inResp == false) { makeBot = true; }
if (makeBot == true)
{
botPref = Instantiate(botPrefab, this.transform.position +
this.transform.forward, this.transform.rotation);
botPref.name = botName;
makeBot = false;
}
}
void OnTriggerEnter(Collider other)
{
GameObject go = other.transform.gameObject;
if (go != null) { inResp = true; }
else { inResp = false; }
}
}
Answer by Llama_w_2Ls · Jan 30, 2021 at 10:30 AM
Could you reset the transform of botPrefab? Possibly the prefab itself in one forward on the z axis, causing it to look like it spawns at 501, instead of 500.
All of the axes (x, y, z) for the bot prefab are zeroed, the problem still exists
Answer by kuba86699 · Jan 30, 2021 at 12:15 PM
I was able to fix the problem by adding this line of code
botPref.transform.position = this.transform.position;