尝试重复检查变量时发生StackOverflow错误

时间:2018-09-01 01:18:22

标签: c# stack-overflow

嘿,在我开始之前,我想让所有人都知道我不仅是这个论坛的新手,还是Unity和C#本身,所以如果有一个简单的解决方案或其他愚蠢的错误,我深表歉意。

好了,基本上,我想做的就是在玩家进入太空时切换其重力,为实现此目的,我正在检查玩家的transform.position.y并查看其是否在指定的高度,是否不在指定高度。我加力。

代码区域:

private void ChangeGravity()
    {
            if (rb.position.y >= 10f)
            {
                SAF = false;
                rb.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionZ;  
            }
            else
            {
                rb.AddForce(0, VerticalForce * Time.deltaTime, 0);
                ChangeGravity();
            }
    }

为澄清起见,SAF是一种预防措施,以使播放器无法向空格按钮发送垃圾邮件。 另外,VerticalForce = 2f,通过我的测试,我确定if语句可能为真(此测试通过将y设置为10)

现在这是错误:

StackOverflowException
UnityEngine.Rigidbody.AddForce (Vector3 force, ForceMode mode)
UnityEngine.Rigidbody.AddForce (Single x, Single y, Single z) (at C:/buildslave/unity/build/Runtime/Dynamics/ScriptBindings/Dynamics.bindings.cs:171)
PlayerMovement.ChangeGravity () (at Assets/Scripts/PlayerMovement.cs:21)
PlayerMovement.ChangeGravity () (at Assets/Scripts/PlayerMovement.cs:22)
(The final line repeats a bunch but I cut that out)

整个脚本:The Script


编辑

我终于找到了一个非常有用的教程,如果没有你们,我将找不到如何反转对象重力的教程,这使这个问题过时了,​​谢谢您的时间,对不起,我在制作之前没有找到这个问题。

1 个答案:

答案 0 :(得分:0)

您的方法不会返回,它会自行调用,然后再次调用自身。

由于调用函数会在线程的堆栈上分配一些内存,因此该堆栈很快就会溢出,因为它的空间限制为几兆字节。

在while循环中调用此方法,在满足条件时中断循环。因此,在循环的每次迭代中,方法都会返回,并且调用堆栈不会增长。

   while (true)
   {
        if (rb.position.y >= 10f)
        {
            SAF = false;
            rb.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionZ;  
            break; //break the loop since condition is met
        }
        else
        {
            rb.AddForce(0, VerticalForce * Time.deltaTime, 0);
            continue; //the condition is not met, so the loop goes on
        }
    }