- Home /
Question by
AryaIsMe · Apr 28, 2021 at 09:08 PM ·
c#bugvisual studio
In my game there is a bug that happens which freezes everything and I know what causes it but I am unsure how to fix it
Basically whenever I press play in my game the game freezes and I can't do anything. I have to use task manager to close it. I know it comes from this script but I am unsure where it comes from. This script spawns in a special type of zombie. I know it is this script because I deactivated it and the game worked.
Edit: I found out that it was because of the prefab not the script.
Behemoth Zombie spawner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BehemothRandSpawn : MonoBehaviour
{
public GameObject ZK;
public int xPos;
public int zPos;
public int enemyCount;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 10; i++)
{
xPos = Random.Range(1, 165);
zPos = Random.Range(1, 215);
Instantiate(ZK, new Vector3(xPos, 0.3f, zPos), Quaternion.identity);
enemyCount = enemyCount + 1;
}
}
}
Comment
Answer by HellsHand · Apr 28, 2021 at 10:02 PM
You may wanna spawn them in Update()
1 by 1. Something like this will spawn 10 enemies in 1 second at 30 fps:
int toSpawn = 30; //actual fps
void Update()
{
if(toSpawn > 0 && toSpawn % 3 == 0) //The 3 is fps divided by 10, so 60 fps would be 6 and so on
{
xPos = Random.Range(1, 165);
zPos = Random.Range(1, 215);
Instantiate(ZK, new Vector3(xPos, 0.3f, zPos), Quaternion.identity);
enemyCount = enemyCount + 1;
toSpawn--;
}
else
{
toSpawn--;
}
}
At 30 fps, in the Start()
method, you will be creating 10 prefabs in 1/30 of a second which can be quite taxing. If each of those prefabs has a Start()
method to run it gets even worse.