【问题标题】:Why does why C# code keep crashing Unity? (I'm a beginner to Unity and C#)为什么 C# 代码总是让 Unity 崩溃? (我是 Unity 和 C# 的初学者)
【发布时间】:2023-03-24 08:26:01
【问题描述】:

每当我运行我的游戏时,它都会冻结,但如果没有这个 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 只是崩溃。

【问题讨论】:

    标签: c# unity3d crash


    【解决方案1】:

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

        while (true)
        {
    
        }
    

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2022-12-04
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 1970-01-01
          • 2011-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多