Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Fornoreason1000 · Jan 25, 2016 at 03:08 PM · unityeditorserializationscriptableobjectdelegateevent-handling

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,

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

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.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fornoreason1000 · Jan 26, 2016 at 03:00 AM -1
Share

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

avatar image DrSpritz Fornoreason1000 · Feb 21, 2018 at 06:07 AM 0
Share

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!

avatar image Fornoreason1000 · Jan 26, 2016 at 03:38 AM 1
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

37 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges