- Home /
How to use Delegate and UnityEvents in SerilaizedObject assets Without losing them in PlayTest
Basically I have 2 scripts , my aim is to save a bunch of Method pointers + parameters they might need in a scriptable object assign it to a variable in any trigger scripts i have in the scene then invoke those methods in order.
the first script is Method Container, this will hold the method pointers or Delegates generic List, it also has a nested class for parameter storage.
[System.Serializable]
public class UnityDelegateClass : UnityEvent<MethodContainer.EventDelgateData>
{
}
public partial class MethodContainer: ScriptableObject {
//UnityEvent
public UnityDelegateClass IronUnityEvent;
//UnityAction
public UnityAction<EventDelgateData> action;
//The Generic List for the Events
public List<EventDelgateData> CommandData;
/// <summary>
/// Class that holders any necessary paramters
/// </summary>
[System.Serializable]
public class EventDelgateData
{
public string[] name;
public float[] floats;
public int[] integers;
public Color[] Colors;
}
public void Run()
{
Debug.Log(CommandData[0]);
IronUnityEvent.Invoke(CommandData[0]);
}
///
public void PrintConsole(EventDelgateData data)
{
Debug.Log(data.name[0]);
}
}
Here you see ive tried to implement both C# delegates and UnityEvents, UnityEvents don't work while C# gives a null reference error. The next class is the Snippets is what i Use to create an edit this data from my Editor script. it uses a Layout button to create it.
public void AddDataButton()
{
if(GUILayout.Button("Add Data"))
{
if(Current().IronUnityEvent == null)
{
Current().IronUnityEvent = new UnityDelegateClass();
}
//UnityAction<MethodContainer.EventDelgateData> action = new UnityAction<MethodContainer.EventDelgateData>(Current().PrintConsole);
Current().action = new UnityAction<MethodContainer.EventDelgateData>(Current().PrintConsole);
UnityEventTools.AddPersistentListener(Current().IronUnityEvent, Current().action);
Current().IronUnityEvent.AddListener(Current().PrintConsole);
Current().CommandData.Add(new MethodContainer.EventDelgateData());
Current().CommandData[0].name = new string[] { "Thank You Unity" };
EditorUtility.SetDirty(Current());
AssetDatabase.SaveAssets();
}
}
Originally i Though the C# delegates weren't being serialized was causing this, but then i read that Unity Events can be serialized, so I tried them.
As alternatives I've tries using strings combined with send Message and using integer as an ID codes for each any every method (lots of ifs / big switch stamens).
Any information on what is going on here, and how i can get around this would be greatly appreicated
Thanks
UPDATE Updated the scripts,
Answer by Bunny83 · Jan 25, 2016 at 04:20 PM
I haven't really used the UnityEvent class yet. However i've quickly looked through the implementation and it seems the class has some limitations. First of all that class can be roughly divided into two parts. It allows runtime listeners to any method as well as persistant listeners which are serialized. While the runtime listeners can be any method (static or instance) on any object, persistant listeners can only reference instance methods of a class that is derived from UnityEngine.Object.
When you use the AddListener method you only register a "runtime listener" which isn't serialized at all. It looks like all the methods to register a persistant listener are internal methods. In the editor you would have to use UnityEditor.Events.UnityEventTools.AddPersistentListener()
to actually add a persistant listener.
But as i said persistant listeners can only be instance methods on objects derived from UnityEngine.Object.
The only classes which you can extend that are derived from UnityEngine.Object are:
MonoBehaviour
ScriptableObject
So a persistent listener has to be a method in a class derived either from MonoBehaviour or ScriptableObject. Of course the referenced object has to be serialized either project-wide as asset or along with the referencing UnityEvent. Otherwise Unity has no way to get hold of the needed reference to rebuild the delegate.
Finally i should add that you should not derive your own types from UnityEngine.Object. That class has a special meaning to Unity and is always linked to a native C++ counterpart. If you create an instance of your own UnityEngine.Object derived type it will become a fake-null-object.
Firstly, Thank You for the Answer.
The Inheritance from U*nityEngine.Objec*t was a last ditch effort, I thought because EventDelgateData inherited from System.Object Untiy wouldn't serialize it. (it was late). I have removed it from the class definition. As I Said before I tried this first with C# delgates , but evertyime by the time it got the the Event Interpreter class it was null (Line 14) due to the Deserialization/Serialization Cycle of Unity.
Seems I have few changes to make, namely AddPersistantListener requires a UnityAction(A UnityDelegate) ins$$anonymous$$d of a $$anonymous$$ethod Group. I figured it be simply just top combine $$anonymous$$ethod Container and Event Interpreter, that way i can use this method as isntance methods, and no need to jump over the place. and since $$anonymous$$ethodContainer already Inherits from ScriptableObject, that solves that issue.
However it seems it still not serializing UnityEvent at all (it becomes null when i hit playtest). I have Updated my Question
Fornoreason1000 thanks for the topic! I have same problem and need to add a "persistent" listener, as method in an non UnityEngine.Object class, to UnityEvent. What you mean said
"I figured it be simply just top combine $$anonymous$$ethod Container and Event Interpreter, that way i can use this method as isntance methods"
Can you please show an example how to combine method container?
Thanks!
Turns out the problem was that UnityEvent wasn't serializable , i forogt that i needed to uses the Encapasulating class thta t was marked Serializable at the Top of $$anonymous$$ehodContainer lol
Your answer
Follow this Question
Related Questions
Board game minimax AI implementation 0 Answers
What are the pros and cons of ScriptableObjects vs. JSON for data files? 2 Answers
"Unbroken Reference" problem when using a custom Editor to Save/Load a ScriptableObject Asset 0 Answers
Some data of scriptable object resets when Unity Editor restarts 0 Answers
Unity Not Loading 0 Answers