检查光线投射的命中是否会导致游戏崩溃



所以我正在尝试检测我是否单击带有"太阳系"标签的对象,如果是,则将该太阳系加载到另一个场景中。 这段代码以前运行良好,但现在它崩溃了,我必须使用结束任务按钮从任务管理器结束 Unity 才能关闭它。 它只是完全停止响应。

以下是我认为在弄乱许多调试后发现错误的代码.log以查找代码停止的位置,从而找出 Unity 停止响应的位置:

    RaycastHit[] hit = Physics.RaycastAll(cursorPosition, Vector3.forward,15f);
        Debug.Log("test2");//this is printed to the console - code crashes below this line
        for(int i = 0; i < hit.Length; i++)
        {
            Debug.Log("hit"); // this is never printed to console - code crashes above this line
            if(currentScene == "Universe")
            {
                if(hit[i].collider.gameObject.tag == "SolarSystem")
                {
                    ChangeScene("SolarSystem");
                    SolarSystem clickedSolarSystem = hit[i].collider.gameObject.GetComponent<SystemObjectLink>().LinkedClass;
                    SolarSystem LoadedSolarSystem = SolarSystemCamera.GetComponent<SolarSystem>() as SolarSystem;
                    LoadedSolarSystem = clickedSolarSystem;
                    Debug.Log("generating system clicked on");
                    if (LoadedSolarSystem.preGenerated == false)
                    {
                        LoadedSolarSystem.Generate();
                    }
                    else
                    {
                        LoadedSolarSystem.Regenerate();
                    }
                    break;
                }
            }
            if(currentScene == "SolarSystem")
            {
                if (hit[i].collider != null)
                {
                    if (hit[i].collider.gameObject.tag == "Planet")
                    {
                        Target = hit[i].collider.gameObject;
                        break;
                    }
                    else if (hit[i].collider.gameObject.tag == "Moon")
                    {
                        Target = hit[i].collider.gameObject;
                        break;
                    }
                    Target = hit[i].collider.gameObject;
                }
            }
        }

我有一个带有硬编码的for(;;)语句

    if(<state>){
        break:
    }

语句来打破无限循环。 但是当我点击游戏中的一个对象时。 它在运行代码之前检查代码是否有任何错误。 当它这样做时,它就会陷入无限循环,所以为了修复它,我做了这个

    for(;errorIndex<99; errorIndex++){
    }

我的错误和我学到的东西:

切勿使用while(true)循环或 for 循环,而无法摆脱自身(for(;;)

如果 Unity 引擎/编辑器停止响应,那是因为它处于无限循环中 - 查看您的代码并确保您的任何循环都不可能永远持续下去

最新更新