Unity зависает на Play - PullRequest
0 голосов
/ 03 апреля 2020

Я делал это enemy generator, которое вызывается на Start(), и оно большую часть времени зависает. Иногда это позволяет играть один раз, но как только я нажимаю кнопку воспроизведения во второй раз, он останавливается, единство необходимо перезапустить. Автономная версия не решает проблему. Регистрирует последние строки:

UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
EnemyGenerator:Start() (at Assets\Scripts\Utils\EnemyGenerator.cs:23)

(Filename: Assets/Scripts/Utils/EnemyGenerator.cs Line: 23)

Вот мой скрипт:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyGenerator : MonoBehaviour
{
    public List<GameObject> camps;
    public List<GameObject> enemies;
    int threshold;


public List<GameObject> campAreas;
public List<GameObject> enemyAreas;

public int campsToSpawn;
public int enemiesPerAreaMin;
public int enemiesPerAreaMax;

void Start()
{
    for (int i = 0; i < campsToSpawn; i++)
    {
        threshold = Random.Range(0, camps.Count - 1);
        Debug.Log(threshold);
        var campPlace = Random.Range(0, campAreas.Count - 1);
        var camp = Instantiate(camps[threshold], campAreas[campPlace].transform.position, Quaternion.identity);
        if (camp != null)
        {
            campAreas.RemoveAt(campPlace);
        }
    }
    Debug.Break();
    bool canSpawn = true;

    for (int i = 0; i < enemyAreas.Count; i++)
    {
        threshold = Random.Range(0, enemies.Count - 1);
        List<GameObject> enemiesSpawned = new List<GameObject>();
        var enemyCount = Random.Range(enemiesPerAreaMin, enemiesPerAreaMax);
        for (int j = 0; j < enemyCount; j++)
        {
            var pos = new Vector3(Random.Range(enemyAreas[i].GetComponent<BoxCollider>().bounds.min.x, enemyAreas[i].GetComponent<BoxCollider>().bounds.max.x), enemyAreas[i].transform.position.y,
                    Random.Range(enemyAreas[i].GetComponent<BoxCollider>().bounds.min.z, enemyAreas[i].GetComponent<BoxCollider>().bounds.max.z));
            if (enemiesSpawned.Count == 0)
            {
                GameObject en = null;
                enemiesSpawned.Add(en = Instantiate(enemies[threshold], pos, Quaternion.identity));
            }
            else
            {
                for (int x = 0; x < enemiesSpawned.Count; x++)
                {
                    if (Vector3.Distance(enemiesSpawned[x].transform.position, pos) < 3f)
                    {
                        canSpawn = false;
                    }
                }
                if (!canSpawn)
                {
                    j--;
                }
                else
                {
                    enemiesSpawned.Add(Instantiate(enemies[threshold], pos, Quaternion.identity));
                }
            }
        }
        Debug.Break();
    }
}
}

Я пытался найти что-то, что на самом деле Я навсегда, но я не думаю, что это проблема. Хотите знать, может ли это быть утечка производительности?

Спасибо заранее.

1 Ответ

0 голосов
/ 03 апреля 2020

Извините, хотя это была проблема с Debug.Break ();

Вероятно, это проблема

           {
               for (int x = 0; x < enemiesSpawned.Count; x++)
               {
                   if (Vector3.Distance(enemiesSpawned[x].transform.position, pos) < 3f)
                   {
                       canSpawn = false;
                   }
               }
               if (!canSpawn)
               {
                   j--;
               }
               else
               {
                   enemiesSpawned.Add(Instantiate(enemies[threshold], pos, Quaternion.identity));
               }
           }
You getting a random position inside a certain bounds. If the position is too close u don't spawn and --j; to retry a new position. So if for some reason the bounds are wrong or barely engouth you might be running that function for a very long time.

A quick test is to add a counter before your j for loop.


int debugCounter = 0;
for (int j = 0; j < enemyCount; j++)
       {
//at the very top
++debugCounter;
if(debugCounter > 100)//or a bigger number
{
Debug.Log("Too many attemps");
break;
}
...
...