首页 > 解决方案 > 我的脚本无法按预期工作,它还会使统一编辑器崩溃

问题描述

我已经在这个项目上工作了几天,我遇到了一个似乎无法解决的错误,因为不仅没有出现错误消息,而且它还“跳过”了我的调试消息并使编辑器本身崩溃。

以下脚本是一个对话框显示器,显然是导致问题的原因(请原谅混乱的代码,我在尝试解决问题时弄乱了它):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class DialogDisplayer : MonoBehaviour
{
    [SerializeField] Dialog[] dialogFiles;
    TextMeshPro outputTxt;

    bool next, finished;
    char comma = (char)44;
    char period = (char)46;

    // Use this for initialization
    void Start()
    {
        outputTxt = GetComponent<TextMeshPro>();
        StartCoroutine(type());
    }

    IEnumerator type()
    {
        int dialogIndex = 0;

        do
        {
            foreach (char c in dialogFiles[dialogIndex].dialogText)
            {
                if (Input.GetKeyDown(KeyCode.Z))
                {
                    outputTxt.text = dialogFiles[dialogIndex].dialogText;
                    Debug.Log("z pressed in the foreach");
                    break;
                }

                outputTxt.text += c;
                if (c == ' ')
                    continue;

                if (dialogFiles[dialogIndex].delayforPunctuations)
                {
                    if (c == comma)
                        yield return new WaitForSeconds(dialogFiles[dialogIndex].delayBetweenLetters + 0.1f);
                    else if (c == period)
                        yield return new WaitForSeconds(dialogFiles[dialogIndex].delayBetweenLetters + 0.2f);
                    else
                        yield return new WaitForSeconds(dialogFiles[dialogIndex].delayBetweenLetters);
                }
                else
                    yield return new WaitForSeconds(dialogFiles[dialogIndex].delayBetweenLetters);
            }
            Debug.Log("Either finished or broken out of the loop");

            while (!finished)
            {
                Debug.LogWarning("Entering while loop");
                if (Input.GetKeyDown(KeyCode.Z))
                {
                    Debug.Log("entered if");
                    finished = true;
                    dialogIndex++;
                }
                Debug.Log("got out");
            }

        } while (dialogIndex != dialogFiles.Length - 1);
    }
}

标签: c#unity3d

解决方案


从我所见......

In English: 只要 dialogIndex 不等于 dialogFiles.length 减一,您的脚本就会崩溃。

一旦这样:

while (dialogIndex != dialogFiles.Length - 1);

是的,它进入了一个无限循环。一旦 dialogFiles.Length -1 不再等于 dialogIndex,就没有指示该做什么了。

不确定您要使用那里的最后一行代码来完成什么,但计算机也不是,一旦满足这些条件,它只会等待指令......永远。

它需要是

while (dialogIndex != dialogFiles.Length - 1); {
  Do Something;
  provide Action To Eventually escape this loop (make dialogIndex = dialogFiles.Length - 1)
}

至于评论说,你可以做StartCoroutine(type());StartCoroutine("type"); 没关系。


推荐阅读