Saving the transform not just the position

If you notice when you restore you are facing a different direction than when you saved. To fix this you can use something like this:

using System;
using UnityEngine;

namespace RPG.Saving
{
    [System.Serializable]
    public class SerializableTransform
    {
        float px, py, pz;
        float rx, ry, rz, rw;

        public SerializableTransform(Transform transform)
        {
            px = transform.position.x;
            py = transform.position.y;
            pz = transform.position.z;

            rx = transform.rotation.x;
            ry = transform.rotation.y;
            rz = transform.rotation.z;
            rw = transform.rotation.w;
        }

        public Tuple<Vector3, Quaternion> ToTransform()
        {
            return new Tuple<Vector3, Quaternion>(new Vector3(px, py, pz), new Quaternion(rx, ry, rz, rw));
        }
    }
}

and then use it in the mover like this:

        public object CaptureState()
        {
            return new SerializableTransform(transform);
        }

        public void RestoreState(object state)
        {
            if (state is SerializableTransform posRot)
            {
                GetComponent<NavMeshAgent>().enabled = false;
                transform.position = posRot.ToTransform().Item1;
                transform.rotation = posRot.ToTransform().Item2;
                GetComponent<NavMeshAgent>().enabled = true;
            }
        }

A good tip!

Oh and if you don’t like Item1 and Item2 and prefer something more readable you can use something like this:

        public (Vector3 Position, Quaternion Rotation) ToTransform()
        {
            return new (new Vector3(px, py, pz), new Quaternion(rx, ry, rz, rw));
        }

And then use it like this:

        public void RestoreState(object state)
        {
            if (state is SerializableTransform posRot)
            {
                GetComponent<NavMeshAgent>().enabled = false;
                transform.position = posRot.ToTransform().Position;
                transform.rotation = posRot.ToTransform().Rotation;
                GetComponent<NavMeshAgent>().enabled = true;
            }
        }
1 Like

It might be different on more recent versions of Unity (or even with 2018.3 whereas I used the last 2018 version 2018.4), but I got error messages about it.

This worked for me instead:

       public (Vector3 Position, Quaternion Rotation) ToTransform()
        {
            return (new Vector3(px, py, pz), new Quaternion(rx, ry, rz, rw));
        }

(just remove one new)

Privacy & Terms