简体   繁体   English

为什么C#代码为什么会不断使Unity崩溃? (我是Unity和C#的初学者)

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

Whenever I run my game it freezes, but it doesn't without this C# script. 每当我运行我的游戏时,它都会冻结,但并非没有C#脚本。

I've tried changing around my code, and it works outside of Unity, in .NET (with some tweaks to certain functions) but when it's in Unity it crashes. 我尝试过更改代码,并且它可以在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);
    }
}

It should decrease and increase the force value, then stop when you press E, but Unity just crashes. 它应该减小并增大力值,然后在按E时停止,但是Unity崩溃了。

i belive that unity starts catching key strokes after the first frame, not before, try moving fstart() behind a first run bool in the FixedUpdate function 我相信团结会在第一帧之后而不是之前开始捕捉击键,请尝试在FixedUpdate函数中将fstart()移到第一次运行的布尔之后

oh and this will hang the entire program every time it executes a frame..... 哦,这将在每次执行框架时将整个程序挂起.....

Unity takes care of the while(true) for you. Unity为您照顾while(true) Unity's while(true) calls your FixedUpdate , you just need to fill it in. Unity的while(true)调用了FixedUpdate ,您只需要填写即可。

Unity only captures keystrokes once per frame, so Input.GetKey(KeyCode.E) will always return the same value. Unity每帧仅捕获一次击键,因此Input.GetKey(KeyCode.E)将始终返回相同的值。 Unity crashes because of your while(true) is an infinite loop. 由于您的while(true)是一个无限循环,因此Unity崩溃了。

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

The code crashes because you have an infinite loop here: 代码崩溃是因为您在此处存在无限循环:

    while (true)
    {

    }

It will never exit the loop so nothing more happens. 它永远不会退出循环,因此不再发生任何事情。 Just put that code into Update() method, which gets called by the engine on every frame, it will do the trick 只需将代码放入Update()方法中,引擎就会在每一帧中调用该方法,从而达到目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM