简体   繁体   中英

StackOverflow error when trying to repeatedly check a variable

Hey before I start I want to let everyone know I'm not only new to this forum but Unity and C# itself so I apologize if there is an easy solution or other silly mistakes.

Alright so basically what I am trying to do is switch the gravity of my player when they hit space, to achieve this I am checking the players transform.position.y and seeing if it is at it's designated height and if it's not I add force.

The area of code:

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();
            }
    }

For clarification SAF is a precautionary measure so that the player can't spam the space button. Also VerticalForce = 2f and through my testing I have determined that it is possible for the if statement to be true (this test was by setting the y to 10)

Now here's the error:

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 Entire Script: The Script


EDIT

I finally found a very helpful tutorial that i wouldnt have found without you guys on how to reverse gravity of an object, this makes this question obsolete, thank you for your time i'm sorry i didn't find this before making the question.

Your method does not return, it calls itself which in turn calls itself again.

Since calling a function allocates some memory on the thread's stack, the stack is soon overflowed since it has a space limit of a few MegaBytes.

Call this method in while loop, break the loop when the condition is met. So in each iteration of the loop the method is returned and the call stack won't grow.

   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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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