How to save parent/child relationships, positions, rotations etc.

Hello,
Let’s say I have 3 objects: ObjectA, ObjectB, Object C. ObjectB is a child of ObjectA and Object C is a child of Object B. Each of these objects is set initially with a particular position, rotation, localPosition, localRotation etc.

Next, assume that (via script) the position and rotation of each of these objects gets changed.
Once this has happened, How can I revert back to their original positions/rotations? It seems like this should be an easy thing to do, but I’m struggling a bit to figure out the code for this. thanks!

Add this script to anything that needs its position saved and reverted to:

using UnityEngine;
using System.Collections;

public class PositionSave : MonoBehaviour {
    private Transform savedTransform;

    public void SavePosition()
    {
        savedTransform = this.transform;
    }

    public void RestorePosition()
    {
        this.transform.position = savedTransform.position;
        this.transform.rotation = savedTransform.rotation;
        this.transform.localScale = savedTransform.localScale;
    }
}

Then other objects can call the public Save/Restore methods on this GameObject. You can also add a Start() function to this script that has a SavePosition call so all the objects will save their Position when the load up. They could also restore themselves based on certain condition in Update if you needed that.

Note if an object is a child of another object. And you save load its original position without restoring its parent’s transform it might not end up where it started. Since its stuff is all relative to the parent. Or if the parent gets a Save call, then things change … THEN the child gets a save call they will be out of sync. So you you have to make sure you Save/Load all the parent->children at the same time or things could get wonky

Hey thanks! I’ll check this out. For objects that are children, we need to also set localPostion and localRotation correct?

Actually no. setting position will set localPosition and vice versa.
On any of the 3 (position,rotation,scale). The numbers in those variables are the absolute values of their position/rotation/scale in the world. localXXX is the relative position/scale/rotation to the parent. If you don’t have a parent these 2 numbers will be equal. But setting one will always set the other, because they aren’t independent. If My parent is at 10,10,10 and I set my localPosition to 10,10,10 this will necessarily force my position to be 20,20,20. Conversely in the same situation (parent is at 10,10,10) if I set my position to 5,5,5 then my localPosition will be set to -5,-5,-5.

Edit: I just noticed I had a localScale instead of scale. This is purely random chance from typing fast and intellisense popping up localScale first and me not noticing.

I think you’re right to use localScale. Because you can’t assign a lossyScale, it’s readonly.