Best way to set game object transforms
Hi there. I have a system that records a characters transform for a given frame into an array of Transforms so that I can play them back layter on. Basically recording character movement for playback.
The trouble is that you can't simply set the game object's transform back to the one you previously recorded (for some reason transforms are read only). So you have to loop through all the transforms and assign each property separately (postion, rotations, scale, etc...)
But characters have a hierarchy of transforms (each bone has its own) that needs to be set.
Anyone have any suggestions on what the best approach would be to assign the whole hierarchy of the saved transform to the character game object transform?
thanks
Answer by SuperSpasm · Jan 16, 2017 at 04:00 AM
I think the best solution to your problem is to abstract the actual copying, to mimick what you would do if you could set your transform from code/ instantiate new transforms
EDIT: previous version of this answer used a class derived from Transform, turns out that causes errors if you instantiate it in the way I showed.
you can't instantiate new Transforms, but you can make a new class that can store the information you need from them. you could try something like this:
public class Trans2
{
public Vector3 position;
public Quaternion rotation;
public Vector3 localScale;
public Trans2(Transform trans)
{
this.position = trans.position;
this.rotation = trans.rotation;
this.localScale = trans.localScale;
}
}
then to simplify loading from a saved transform you could add an extention method in a static class, something like so:
public static class TransformExtention{
public static void LoadTrans(this Transform original, Trans2 savedCopy)
{
original.position = savedCopy.position;
original.rotation = savedCopy.rotation;
original.localScale = savedCopy.localScale;
}
}
( you can add whichever Transform members you need to keep track of in the constructor and LoadTrans method)
after that, saving/loading should look something like this:
Trans2 savedTrans = new Trans2(gameObject.transform); // saving
gameObject.transform.LoadTrans(savedTrans);
you could also have an extention method for saving, but you'd have to instantiate your Trans2 object anyway. There are many more ways to do this, but the bottom line is you can abstract the actual getting/setting of transform properties so you don't have to write it many times in your code
Answer by TheyLeftMe4Dead · Jan 16, 2017 at 03:27 AM
I have a few ideas. I've never done this or know if it's possible, but you could try to make your system create an animation (your recording) then you could play it back later without having to deal with complicated Transforms. Otherwise, the only other way I know is to simply loop through each recorded movement and set it to your recording as you said.
Your answer
![](https://koobas.hobune.stream/wayback/20220612104354im_/https://answers.unity.com/themes/thub/images/avi.jpg)