- Home /
Serializing a Transform instance in a custom inspector window
Hi all! Im trying to create a custom inspector for level generation. I have run into some troubles tho.
I want to serialize a Transform object so it will persist between Play sessions and also when Unity has quit.
I made a test case for you to look at that will illustrate my problem:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class MyWindow : EditorWindow {
[SerializeField]
private Props props;
[MenuItem("Test/Test")]
public static void ShowWindow() {
EditorWindow.GetWindow(typeof(MyWindow),false,"Test");
}
void OnEnable() {
if(props == null) {
props = new Props();
}
}
void OnGUI() {
props.OnGUI();
}
}
[System.Serializable]
public class Props {
[SerializeField]
public Transform parent;
public void OnGUI() {
parent = EditorGUILayout.ObjectField("Parent Transform",parent,typeof(Transform),true) as Transform;
}
}
I've created a window which shows a field to which you can drag an object from the hierarchy panel. All works fine but when restart Unity or press Play and Stop, the field is "None" and the reference is lost.
I have tried to follow the best practices on this, but clearly something has gone wrong.
Anyone know what the problem is?
Thanks!
Answer by MakeCodeNow · Mar 05, 2014 at 07:17 PM
A Transform member var is a reference to the transform, not the transform itself. If you want to have the Transform serialzied, make a prefab out of it. If you don't want to make a prefab, you'll need to manually extract properties from the transform, save them in individual Vector3/Quat/etc properties, and then create a new Transform/GameObject on start.
Thanks for answering! Ok, it makes sense that Unity doesn't serialize references to Transform objects. But I'm not sure what you mean by making a prefab? I have to, some how, serialize the instance of the prefab. Along with all its children.
The level generator works like this: You drag a parent transform to the custom inspector window. Then you hit a GENERATE button and a level is built by instanciating prefabs of various kind and added to the hierarchy using the the mentioned parent transform as parent. All the children are stored in a List. But since the parent transform isn't serialized then neither is the list of children.
Answer by Aledend · Apr 11, 2020 at 07:20 PM
Old post but the first one that showed up on google. My workaround has been having the generation happen outside playmode and saving the instances in the scene. On startup the reference to each instance would have to be rebound with the likes of GameObject.Find and Transform.Find...
It's just a do once thing and my project's small.. so I can't tell wether this is viable when working with a larger amount of gameobjects.