Correct way to serialized in custome editor? - unity3d

this is test script
public class Test : MonoBehaviour
{
public int something;
}
1.if i directly set the value without use serializedProperty
[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
private Test test;
private void OnEnable()
{
test = target as Test;
}
public override void OnInspectorGUI()
{
test.something = EditorGUILayout.IntField("Something", test.something);
if (GUI.changed)
EditorUtility.SetDirty(this);
}
}
value is saved successfully in editor
result
but if i restart unity,the value will be reset,this means the value is not serialized to disk?
2.if use serializedProperty
[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
var something = serializedObject.FindProperty("something");
something.intValue = EditorGUILayout.IntField("Something", something.intValue);
serializedObject.ApplyModifiedProperties();
}
}
everything is right
my question
why first way can save value in editor but not serilized to disk? is my script something wrong?
what's the true difference bewtween them?
second way is the correct way to serilized?

You should use SerializedProperty class for editing properties on objects in a completely generic way that automatically handles undo and styling UI for Prefabs.
[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
SerializedProperty something;
void OnEnable()
{
/* Fetch the objects from the GameObject script to display in the inspector */
something = serializedObject.FindProperty("something");
}
public override void OnInspectorGUI()
{
/* Update the serializedProperty - always do this in the beginning of OnInspectorGUI. */
serializedObject.Update();
/* Display your field in the inspector */
EditorGUILayout.PropertyField(something);
/* Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI. */
serializedObject.ApplyModifiedProperties();
}
}

Related

Calling protected variable from another class

I need to call a protected variable from a public class into an if statement in a private method of another public class
I am programing a video game in unity and I need to use a bool variable (that shows if the character is out of stamina) in an if statement to determine whether or not the character can run
This is what my code looks like excluding everything unrelated to the problem
Public class CharacterStats : MonoBehaviour
{
[SerialzeField] protected bool Tired;
}
Public class PlayerMovement : MonoBehaviour
{
Private void HandleRunning()
{
If (Input.GetKeyDown(KeyCode.LeftShift) && X != True)
{
Speed = RunSpeed;
}
}
}
X is where I want the Tired variable to be.
Use a public readonly property like e.g.
public class CharacterStats : MonoBehaviour
{
// Keep you serialized field protected
[SerialzeField] protected bool tired;
// Have a public read-only accessor property
public bool Tired => tired;
}
and then e.g.
public class PlayerMovement : MonoBehaviour
{
// Somehow you will need to get a reference to the CharacterStats instance
// e.g. via the Inspector
[SerializeField] private CharacterStats stats;
[SerializeField] private float RunSpeed;
private float Speed;
private void HandleRunning()
{
if (Input.GetKeyDown(KeyCode.LeftShift) && !stats.IsTired)
{
Speed = RunSpeed;
}
}
}
Alternatively (and my apologies to #aybe who had answered this) you can actually directly serialize a property using explicitely
[field: SerializeField] public bool Tired { get; protected set; }
this is a property which can be accessed by everyone but only this and inherited classes (and due to the serialization now the Inspector) have the permission to set the value.
In general: Fix your casing! In c# all keywords are lower key!

Serialisation not working when inheriting from monobehaviour

Im trying to do a property drawer for a class that i need to be updated as well as editable from the editor.
If i make the class a monobehaviour the serialisation stops working, but if i remove the monobehaviour inheritance it wont update with the game loop.
Is there any way to have both? I would need the object to be able to instantiate with default (empty) values if a monobehaviour script has non instantiated reference.
[Serializable]
public class MySmallTestProp : MonoBehaviour, ISerializationCallbackReceiver
{
[SerializeField]
private string name;
[SerializeField]
private string _name;
[SerializeField]
private float _someFloat;
public float someFloat;
public MySmallTestProp()
{ }
public void OnBeforeSerialize()
{
_name = name;
}
public void OnAfterDeserialize()
{
name = _name;
}
}
[CustomPropertyDrawer(typeof(MySmallTestProp))]
public class MySmallTestPropPropertyDrawer : PropertyDrawer
{
float rowHeight;
int rowSpacing = 5;
int index;
Rect currentPosition;
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
rowHeight = base.GetPropertyHeight(prop, label);
var rows = 2;
if (Application.isPlaying)
{
rows++;
}
else
{
rows++;
}
return rowHeight * rows;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
index = 1;
currentPosition = position;
EditorGUI.BeginProperty(position, label, property);
var nameProp = property.FindPropertyRelative("_name");
EditorGUI.PropertyField(NextPosition(), nameProp, new GUIContent("Name"));
EditorGUI.EndProperty();
}
Rect NextPosition()
{
currentPosition.height = rowHeight;
currentPosition.y = rowSpacing + (rowHeight + rowSpacing) * index++;
return currentPosition;
}
}
So if I understand you correctly what you want to achieve is having a class which is
Serializable
has some default field values
Receives an Update call every frame
Actually I don't think you need any custom property drawer for this.
First two points are as simple as having e.g.
[Serializable]
public class Example
{
// By default this has the value "Default String"
public string someString = "Default String";
// This can be edited only via the Inspector
// by default it is 42
[SerializeField] private float someFloat = 42.0f;
// This is a read-only public access
public float SomeFloat => someFloat;
}
Now to the last and tricky part - the update calls.
The easiest way is to have a dedicated MonoBehaviour like e.g.
public class UpdateDispatcher : MonoBehaviour
{
// Storing the instance for Singleton Pattern
private static UpdateDispatcher _instance;
// Register to this event to receive one call each Update
public static event Action OnUpdate;
// This method is automatically called by Unity when the application is started
// or you enter play mode in the editor
[RuntimeInitializeOnLoadMethod]
private static void Init()
{
// _instsnce is already assigned and alive?
if(_instance) return;
// Otherwise search for one in the scene
_instance = FindObjectOfType<UpdateDispatcher>();
// Found one?
if(_instance) return;
// Otherwise create it now
_instance = new GameObject(nameof(UpdateDispatcher)).AddComponent<UpdateDispatcher>();
}
private void Awake ()
{
// Does another instance already exist?
if(_instance && _instance != this)
{
// Destroy this one
Destroy (gameObject);
return;
}
// Otherwise assign this as the instance and make sure it isn't destroyed when the scene chsnges
_instance = this;
DontDestroyOnLoad (gameObject);
}
private void Update ()
{
// Call the event every frame if something is registered
OnUpdate?.Invoke ();
}
}
And then you can use ISerislizationCallbackReceiver but not for actually doing the serialization (it is already done automatically for the fields) but rather for registration to the update callback like e.g.
[Serializable]
public class Example, ISerializationCallbackReceiver
{
// By default this has the value "Default String"
public string someString = "Default String";
// This can be edited only vis the Inspector
// by default it is 42
[SerializeField] private float someFloat = 42.0f;
// This is a read-only public access
public float SomeFloat => someFloat;
// Nothing to do here, only needed for the interface
public void OnBeforeSerialize() { }
public void OnAfterDeserialize()
{
// Register to the Update event
// It is save to unregister before registering even if we haven't been registered before
// this makes sure we are registered only exactly once
UpdateDispatcher.OnUpdate -= Update;
UpdateDispatcher.OnUpdate += Update;
}
private void Update ()
{
someFloat += Time.deltaTime;
}
}
This answer should be more like a comment, but due to the extension I've decided to post it here.
The objective of a PropertyDrawer is to display properties differently on the editor.
To achieve that you need 2 things:
1.One class that inherits from PropertyAttribute, this will be the reference used in your future scripts.
2.Another class that inherits from PropertyDrawer, here you can type HOW to display the attribute.
One implementation example of a property drawer that shows an attribute without leting the user to edit it from editor:
using UnityEditor;
using UnityEngine;
public class DisplayWithoutEdit : PropertyAttribute
{
}
[CustomPropertyDrawer(typeof(DisplayWithoutEdit))]
public class DisplayWithoutEditDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, label, true);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}
Then you can use it on another script doing something like:
[DisplayWithoutEdit] public float randomNumber = 0f;

unity conditional fields custom editor

my goal:
i have a script
public class MyScript: MonoBehaviour
{
public bool A;
public bool B;
}
I need B to be visible only if A is TRUE
i'de done an extention to the script and added UnityEditor in the title
[CustomEditor(typeof(MyScript))]
public class MyEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
MyScript tool = (MyScript) target;
tool.A = GUILayout.Toggle(tool.A, "Flag");
if(tool.A)
{
tool.B= EditorGUILayout.Toggle(tool.B, "Flag");
}
}
}
but nothing really changed.
what did i do wrong?
First of all your class definition is wrong. You either need [Serializable] or the class should inherit from MonoBehaviour if it shall be attached to a GameObject. Either way remove the ()
[Serializable]
public class MyScript
{
public bool A;
public bool B;
}
or
public class MyScript : MonoBehaviour
{
public bool A;
public bool B;
}
Then note that a Custom Editor is only for classes inherting from either a MonoBehaviour or a ScriptableObject. In other cases you will rather have to implement a Custom PropertyDrawer.
You should always try to not directly make changes in the target. You would have to handle a lot of things like marking as dirty, undo/redo etc by yourself...
Rather always go through SerializedPropertys.
Also note that base.OnInspectorGUI(); will draw the default inspector
So assuming MyScript is a MonoBehaviour class
[CustomEditor(typeof(MyScript))]
public class MyEditor : Editor
{
SerializedProperty a;
SerializedProperty b;
// is called once when according object gains focus in the hierachy
private void OnEnable()
{
// link serialized properties to the target's fields
// more efficient doing this only once
a = serializedObject.FindProperty("A");
b = serializedObject.FindProperty("B");
}
public override void OnInspectorGUI()
{
// fetch current values from the real instance into the serialized "clone"
serializedObject.Update();
// Draw field for A
EditorGUILayout.PropertyField(a);
if(a.boolValue)
{
// Draw field for B
EditorGUILayout.PropertyField(b);
}
// write back serialized values to the real instance
// automatically handles all marking dirty and undo/redo
serializedObject.ApplyModifiedProperties();
}
}
Or if MyScript is actually not a MonoBehaviour then as PropertyDrawer which works basically very similar except you have to use the EditorGUI versions of the fields always requiring a position Rect as parameter:
[CustomPropertyDrawer(typeof(MyScript), true)]
public class MyEditor : PropertyDrawer
{
private bool isUnFolded;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// draw folder for the entire class
isUnFolded = EditorGUI.Foldout(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), isUnFolded, label);
// go to the next line
position.y += EditorGUIUtility.singleLineHeight;
// only draw the rest if unfolded
if (isUnFolded)
{
// draw fields indented
EditorGUI.indentLevel++;
// similar to before get the according serialized properties for the fields
var a = property.FindPropertyRelative("A");
var b = property.FindPropertyRelative("B");
// Draw A field
EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), a);
position.y += EditorGUIUtility.singleLineHeight;
if (a.boolValue)
{
// Draw B field
EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), b);
}
// reset indentation
EditorGUI.indentLevel--;
}
}
// IMPORTANT you have to implement this since your new property is
// higher then 1 single line
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
// default is 1 single line
var height = 1;
// if unfolded at least 1 line more, if a is true 2 lines more
if(isUnFolded) height += (property.FindPropertyRelative("A").boolValue ? 2 : 1);
return height * EditorGUIUtility.singleLineHeight;
}
}

Test Unity method that uses local private SerializedField

I would like to check the content of clockText.text after a couple of seconds.
public class Clock : MonoBehaviour
{
[SerializeField]
TextMeshProUGUI clockText;
TextMeshProUGUI ClockText { get { return clockText; } }
float remainingSeconds = 0f;
public void StartCountDown(int seconds)
{
remainingSeconds = seconds;
}
private void Update()
{
remainingSeconds -= Time.deltaTime;
ClockText.text = Math.Ceiling(remainingSeconds).ToString();
}
}
With this test:
public class TestClock
{
[UnityTest]
public IEnumerator ClockShowCorrectTime()
{
var clock = new GameObject().AddComponent<Components.Shot.Clock>();
clock.StartCountDown(2);
yield return new WaitForSeconds(1);
Assert.AreEqual("00:01", clock.ClockText.text);
}
}
but of course clock.ClockText is null. And I would like to keep clockText as private, so I can't set clockText from the Test.
Should it be public because we can change it on Editor?
Creating a new instance of Clock will not have its clockText member variable set because it's only settable in an inspector window, or when deserializing.
So your test will only work if you make clockText a public variable and set it yourself.
Another workaround is removing your dependency on a text field altogether and make the time value just a private string variable (with a public getter) so your clock can also run without a display field.

How to display & modify array in the Editor Window?

I have GameObject array field in my CustomEditor class derived from the UnityEngine.Editor. I need to be able to display (draw) and give user ability to modify that array.
Just like how Unity's Inspector doing this for Serializable fields of objects derived from the ScriptableObject. E.g. displaying materials array in the inspector:
Refer to yours editor object as to the SerializedObject and then find any required property, draw it, and apply modification:
public class MyEditorWindow : EditorWindow
{
[MenuItem("Window/My Editor Window")]
public static void ShowWindow()
{
GetWindow<MyEditorWindow>();
}
public string[] Strings = { "Larry", "Curly", "Moe" };
void OnGUI()
{
// "target" can be any class derived from ScriptableObject
// (could be EditorWindow, MonoBehaviour, etc)
ScriptableObject target = this;
SerializedObject so = new SerializedObject(target);
SerializedProperty stringsProperty = so.FindProperty("Strings");
EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
so.ApplyModifiedProperties(); // Remember to apply modified properties
}
}
Original answer here.
I managed to do it with a for loop and an extra int:
using UnityEditor;
using UnityEngine;
public class RockSpawner : EditorWindow
{
int rockCollectionSize = 0;
GameObject[] rockCollection;
[MenuItem("Tools/Rock Spawner")]
public static void ShowWindow()
{
GetWindow(typeof(RockSpawner));
}
void OnGUI()
{
rockCollectionSize = EditorGUILayout.IntField("Rock collection size", rockCollectionSize);
if (rockCollection != null && rockCollectionSize != rockCollection.Length)
rockCollection = new GameObject[rockCollectionSize];
for (int i = 0; i < rockCollectionSize; i++)
{
rockCollection[i] = EditorGUILayout.ObjectField("Rock " + i.ToString(), rockCollection[i], typeof(GameObject), false) as GameObject;
}
}
}
The top answer didn't work well for me because the properties did not update, there for I moved the declaration lines to the OnEnable function you do not want to declare them over and over again) and used to so.Update() to update the changed variables.
using UnityEngine;
using UnityEditor;
public class MyEditorWindow : EditorWindow
{
[MenuItem("Window/My Editor Window")]
public static void ShowWindow()
{
GetWindow<MyEditorWindow>();
}
public string[] Strings = { "Larry", "Curly", "Moe" };
SerializedObject so;
private void OnEnable()
{
ScriptableObject target = this;
so = new SerializedObject(target);
}
void OnGUI()
{
// "target" can be any class derived from ScriptableObject
// (could be EditorWindow, MonoBehaviour, etc)
so.Update();
SerializedProperty stringsProperty = so.FindProperty("Strings");
EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
so.ApplyModifiedProperties(); // Remember to apply modified properties
}
}
Links:
Base for my answer
SerializedObject.Update
public GameObject[] yourGameObjects;
Then in the inspector set your size, and fields should open up.
add a public array to your script
public GameObject[] myObjects