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 Clet_ · Jan 04, 2016 at 06:49 PM · componentsattributeassignment

Self-assigning field in class

I've created an attribute I put on fields of a certain class to allow self-assignment of other components attached to itself. Here's the code :

SelfAssignAttribute.cs

 using System;
 using UnityEngine;
 
 [AttributeUsage(AttributeTargets.Field)]
 public class SelfAssignAttribute : PropertyAttribute 
 {
     public SelfAssignAttribute() { }
 }

SelfAssigningAttributeEditor.cs

 using UnityEditor;
 using UnityEngine;
 
 [CustomPropertyDrawer(typeof(SelfAssignAttribute)]
 public class SelfAssignAttributeEditor : PropertyDrawer
 {
     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) 
     {
         //This is a short version stripped of validation to show the general idea of the attribute
         if(property.objectReferenceValue == null) 
         {
             MonoBehaviour mb = (property.serializedObject.targetObject as MonoBehaviour);
             property.objectReferenceValue = mb.transform.GetComponent(fieldInfo.FieldType);
         }
     }
 }

It sure works as intended, but only when OnInspectorGUI is called on said GameObject which fields are tag with [SelfAssignAttribute]. The problem is, I'd like this assignment to occur when scripts are being rebuilt.

Is there a better way than scanning every object in the scene using [UnityEditor.Callbacks.DidReloadScript] in every scene of the project?

Comment
Add comment · Show 1
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 Clet_ · Jan 04, 2016 at 06:50 PM 0
Share

I know I could assign those fields on the Awake() function, but I'd like to avoid writing those lines in every class with this kind of fields

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Bunny83 · Jan 05, 2016 at 02:46 PM

Unfortunately there's no way around your "scanning every object". Keep in mind that an attribute instance is part of the class, not part of a particular instance of that class. That means just your attribute class alone doesn't know about any instances of classes that might have fields with that attribute attached.

Your propertydrawer solution is quite nice, but as you figured out the code only runs when the object is inspected. The inspector is the connection between object instance and your static attribute data.

So the best way is probably to use a seperate script that has an InitializeOnLoadAttribute which scans all MonoBehaviour instances for your attribute and perform that action from the update delegate to ensure everything is loaded and deserialized.

Something like that:

 using System;
 using System.Reflection;
 using UnityEngine;
 using UnityEditor;
 using System.Linq;
 
 [AttributeUsage(AttributeTargets.Field)]
 public class SelfAssignAttribute : Attribute
 {
     public Type type = null;
 }
 
 [AttributeUsage(AttributeTargets.Field)]
 public class ManagerAttribute : SelfAssignAttribute
 {
 }
 
 [InitializeOnLoad]
 public class SelfAssignHelper
 {
     static SelfAssignHelper()
     {
         EditorApplication.update += OnUpdate;
     }
     static void OnUpdate()
     {
         EditorApplication.update -= OnUpdate; // unsubscribe after first call
         DoSelfAssign();
     }
     [MenuItem("Tools/PerformSelfAssign")]
     static void DoSelfAssign()
     {
         var objs = Resources.FindObjectsOfTypeAll<MonoBehaviour>();
         foreach (var obj in objs)
         {
             if (obj == null)
                 continue;
             var type = obj.GetType();
             var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
             foreach(var field in fields)
             {
                 var attr = field.GetCustomAttributes(true)
                     .Where(a=>a is SelfAssignAttribute)
                     .Cast<SelfAssignAttribute>()
                     .FirstOrDefault();
                 if (attr != null && field.GetValue(obj) != null)
                 {
                     var t = field.FieldType;
                     if (attr.type != null)
                         t = attr.type;
                     var val = obj.GetComponent(t);
                     if (val == null && attr is ManagerAttribute)
                         val = Resources.FindObjectsOfTypeAll(t).FirstOrDefault() as Component;
                     if (field.IsStatic)
                         field.SetValue(null, val);
                     else
                         field.SetValue(obj, val);
                 }
             }
         }
     }
 }

I also scan static fields as well. This usually makes no sense, but for singleton references it might be useful. Keep in mind that if multiple instances of a class exist, only the last one will persist.

I added an optional "type" parameter to the attribute. That allows you to also search for more concrete types if the field type is a base type. You probably never need this but i think it might be useful.

I also added a subclass attribute which allows you to initialize "manager" references. This simply searches the whole scene if GetComponent doesn't return anything. That allows you to initialize references to managers, no matter where they are stored.

Finally i also create a menuitem to manually trigger the field check at any time you like.

That would probably be my approach ^^.

Note: I haven't tested that class yet, so feel free to report any errors if you want to use it ^^.

Comment
Add comment · Show 1 · 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 Bunny83 · Jan 05, 2016 at 02:52 PM 0
Share

ps: I haven't yet seen the "DidReloadScript" attribute. It probably becomes quite useful in the future. I still use the InitializeOnLoad attribute for better backwards compatibility. However if you have problems with InitializeOnLoad you might want to remove the whole update delegate thing and try DidReloadScript on the DoSelfAssign method.

I'm not sure when and from which thread the DidReloadScript callback gets called exactly. So you might need to do some pionier work i guess ^^.

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

33 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

Related Questions

Creating object properties dynamically in unity javascript. 2 Answers

Is RequireComponent[typeof(CustomScript)] possible? 2 Answers

[OnSerialize] and other events doesn't work 0 Answers

Is it possible to add an icon to indicate there is an editor tooltip decorating a variable? 0 Answers

Custom [Require*] attribute 2 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