0
\$\begingroup\$

I have an object with both rigid body and NavMeshAgent attached Which I want to set to a new location on scene change, but there is something weird going on with it.

If I just try to set the position it will not have any effect, If I disable the NavMeshAgent (Stopping it does not work) it will correctly go to the new position, but it will then just fall through the floor, so I must also disable gravity on the rigidbody, but as soon as I switch it back on it will fall through the floor again.

How can I get it to correctly update the position and keep gravity on?

Below is my current code:

IEnumerator setPosition(Vector3 position, Quaternion rotation)
{
    float time = 5.02f;
    this.GetComponent<Rigidbody>().useGravity = false;

    yield return new WaitForSeconds(time);

    this.GetComponent<NavMeshAgent>().enabled = false;

    yield return new WaitForSeconds(time);

    this.transform.position = position;
    this.transform.rotation = rotation;

    yield return new WaitForSeconds(time);
    // Here the object is at the correct position

    this.GetComponent<NavMeshAgent>().enabled = true;
    this.GetComponent<NavMeshAgent>().Resume();
    this.GetComponent<Rigidbody>().useGravity = true;
    // Here the object will fall through the floor
}
\$\endgroup\$
2
  • \$\begingroup\$ Does the player persist from one scene to the next? Make sure the new spawn position is above the ground and try setting the players nav agent 'destination' to the spawn position and then set the player transform position. You should not have to enable or disable gravity or the nav agent. \$\endgroup\$ May 21, 2022 at 16:19
  • 1
    \$\begingroup\$ You say there's a scene change occurring here? We can't see that in your code. Please share a Minimal Complete Verifiable Example of the problem: that is, every line of code and every step of scene setup instructions needed to reproduce this issue in a new, empty project. Once we can reproduce the problem, we can test solutions to be sure they'll work for you. \$\endgroup\$
    – DMGregory
    May 21, 2022 at 16:44

0

You must log in to answer this question.

Browse other questions tagged .