- Home /
The problem with FindObjectOfType and Instantiate.Why is not one object created, but a multiplied copy?
Guys, Problem with FindObjectOfType with Instantiate. There are two classes in class1; I call a method to create an Instantiate object in class2. All classes on different objects. I call through FindObjectOfType The problem is that in this case I create not one object each time, but multiplied by the number of created (1 2 4 * 8, etc.). Who knows what the Trouble?
I think you might get more help if you actually post your code here. Use the 101010 button
Answer by Magso · May 12, 2019 at 06:49 PM
It would be safer to have a boolean change when you press R and make Respawn a coroutine with a while loop.
void Start()
{
StartCoroutine("Respawn");
}
void Update()
{
//One object is created directly
if (Input.GetKeyDown(KeyCode.R))
{
respawnBool = true;
}
}
IEnumerator Respawn()
{
while(true)
{
yield return new WaitForSeconds(0.1f);
if(respawnBool)
{
float a = 0;
float b = 0;
Vector3 respawn = new Vector3(a, b, 0);
int i = Random.Range(0, groups.Length);
Instantiate(groups[i], respawn, Quaternion.identity);
respawnBool = false;
}
}
}
Thanks, your method helped. Additional check helped. Works from another class.
Only the question for me is not closed. I would like for myself to understand why, without additional verification, the creation of an instantiate behaves differently? If it is called directly on a line, then it is always created by one object, if through another class using FindObjectOfType, multiplication of objects is obtained. Although they do the same thing.
If theoretically there are thoughts why, then I would like to hear.