为什么 C# 代码总是让 Unity 崩溃? (我是 Unity 和 C# 的初学者)

Why does why C# code keep crashing Unity? (I'm a beginner to Unity and C#)

每当我 运行 我的游戏都会冻结,但没有这个 C# 脚本就不会。

我试过更改我的代码,它在 Unity 之外工作,在 .NET 中(对某些功能进行了一些调整)但是当它在 Unity 中时它崩溃了。

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

public class Throw : MonoBehaviour
{
    public Rigidbody rb;
    string final = "final:";
    public float force = 1;
    public float accuracy = 0;

    void incto(float amount)
    {
        while (force < amount)
        {
            Debug.Log(force);
            force++;
        }
    }

    void decto(float amount)
    {
        while (force > amount)
        {
            Debug.Log(force);
            force--;
        }
    }

    void fstart()
    {
        while (true)
        {
            force = 1;
            incto(200);
            decto(1);
            if(Input.GetKey(KeyCode.E))
            {

                Debug.Log(final + force);
                break;

            }


        }
    }

    // Start is called before the first frame update
    void Start()
    {
        fstart();

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Debug.Log(force);
    }
}

它应该减少和增加力值,然后当你按 E 时停止,但 Unity 只是崩溃。

我相信 unity 在第一帧之后开始捕捉击键,而不是之前,尝试将 fstart() 移到 FixedUpdate 函数中的第一个 运行 bool 后面

哦,这会在每次执行帧时挂起整个程序.....

Unity 会为您处理 while(true)。 Unity的while(true)调用你的FixedUpdate,你只需要填写即可。

Unity 每帧仅捕获一次击键,因此 Input.GetKey(KeyCode.E) 将始终 return 相同的值。 Unity 崩溃是因为你的 while(true) 是一个无限循环。

更多信息:https://docs.unity3d.com/Manual/ExecutionOrder.html

代码崩溃,因为这里有一个无限循环:

    while (true)
    {

    }

它永远不会退出循环,所以不会再发生任何事情。只需将该代码放入 Update() 方法中,引擎会在每一帧调用该方法,它就可以解决问题