为什么 C# 代码总是导致 Unity 崩溃?(我是 Unity 和 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

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

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

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

我相信

Unity 在第一帧之后而不是之前开始捕获击键,请尝试在 FixedUpdate 函数中将 fstart() 移动到第一次运行的布尔值后面

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

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

    while (true)
    {
    }

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

相关内容

最新更新