0
\$\begingroup\$

I'm making a game where in needs to randomly generate objects on a plane, so I setup a code to spawn Food, but whenever I run the code Unity uses up all my computers memory and 40% cpu. I have a fairly good computer and have no issue with anything else in the project. The code has worked when I called it in FixedUpdate but as soon as I try and call it in an invoke it just breaks everything. I have only started working with unity for less than 24 hours so I don't really know what could be wrong, since I didn't get any errors or warnings.

using System.Collections;
using UnityEngine;

public class SpawnFood : MonoBehaviour
{
public Rigidbody Food;
public float x;
public float y;
public float z;
public Vector3 pos;
public float spawnTime;

void FixedUpdate()
{ 
    Start:
    Invoke("FoodSpawn", spawnTime);
    goto Start;
}

void FoodSpawn()
{
    x = (UnityEngine.Random.Range(-110f, 110f));
    z = (UnityEngine.Random.Range(0.50f, 0.51f));
    y = (UnityEngine.Random.Range(-50f, 51f));
    Vector3 pos = new Vector3(x, z, y);
    Instantiate(Food, pos, Quaternion.identity);
}

}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You might want to read Dijkstra's famous essay goto statement considered harmful. It was written in 1968, but everything in it is still pretty much applicable to modern software development. \$\endgroup\$
    – Philipp
    Commented Jan 31, 2018 at 13:29

1 Answer 1

5
\$\begingroup\$

The label and goto in your FixedUpdate method is an infinite loop equivilent to:

while(true)
{
   Invoke("FoodSpawn", spawnTime);
}

Once the engine executes this method it would never leave it (and would keep queuing new Invokes).

A better option may be using InvokeRepeating in the Start method as indicated in the documentation page.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .