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 RChrispy · Oct 26, 2015 at 02:44 PM · editorcustom-inspectorpropertydrawermethodstypecasting

CustomAttribute on Class or Method ( EDIT: Button to call methods)

Hey Guys,

EDIT: I think the Headline was a little missleading. I just Wanted simple buttons with method functionality.

I was sick to implement custom editors just for simple buttons that is why I tried myself on an CustomAttribute. This is how far I got:

TestClass:

 [System.Serializable]
 public class deleteThis : MonoBehaviour {
 
     [ButtonVoid("Is this button working", "TestButton")]
     public float test = 0;
 
     public void TestButton()
     {
         Debug.Log("Button Pressed!");
     }
 }
 

The Attribute Class:

 public class ButtonVoidAttribute : PropertyAttribute
 {
 
     public string ButtonName = "";
     public string FunctionName = "";
 
 
     public ButtonVoidAttribute(string _ButtonName, string _FunctionToCall)
     {
         ButtonName = _ButtonName;
         FunctionName = _FunctionToCall;
     }
 }

And my Drawer:

 [CustomPropertyDrawer(typeof(ButtonVoidAttribute))]
 public class TestDrawer : PropertyDrawer
 {
 
     // Draw the property inside the given rect
     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
     {
 
         // First get the attribute
         ButtonVoidAttribute tFunction = attribute as ButtonVoidAttribute;
 
         
  
         if(GUI.Button( position ,tFunction.ButtonName))
         {
             //call the function with the tag on
             (property.serializedObject.targetObject as MonoBehaviour).SendMessage(tFunction.FunctionName);
         }
         
     }
 }

And it works the problem is I cant set my CustomAttribute on the function I want or above the class instead it works but only if i set it above a value, this is not my desired behaviour. PICTURE: Also the second parameter is maybe not needed if i could place the attribute above the method and reference it directly somehow, and I obviously cant give parameters to my functions. I am new to property Drawers and Custom attributes.

Any ideas? This could be very handy. ^^

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

2 Replies

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

Answer by RChrispy · Oct 29, 2015 at 01:23 PM

Thanks for your replies @BMayne,

the ContextMenu is realy fast but it is not visible and so others who work on the project cant see the custom functionality. So I worked a little bit and found an awnser. Its like a mixture of PropertyDrawer and DecoratorDrawer.

EDIT: Found an easy Decorator Drawer solution.

  1. It can only be placed on a Field as BMayne told so its not possible to change that

But here is my fast solution and it works quite fine for my purpose. Maybe someone wants an easy and fast way to use custom code without the need to write a lot of CustomEditors. :)

Attribute: using UnityEngine;

 [System.AttributeUsageAttribute(System.AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
 public class SimpleButtonNewAttribute : PropertyAttribute
 {
     private System.Type classType;
     public System.Type ClassType
     {
         get { return classType; }
         set { classType = value; }
     }
 
     private string buttonName = "";
     public string ButtonName
     {
         get { return buttonName; }
         set { buttonName = value; }
     }
 
     private string functionName = "";
     public string FunctionName
     {
         get { return functionName; }
         set { functionName = value; }
     }
 
     private bool above = false;
     public bool Above
     {
         get { return above; }
         set { above = value; }
     }
 
     public SimpleButtonNewAttribute(string _FunctionToCall, System.Type _Type ,bool _Above = false)
     {
         ButtonName = "Method: " + _FunctionToCall + "()";
         FunctionName = _FunctionToCall;
         Above = _Above;
         ClassType = _Type;
     }
 }
 

DecoratorDrawer

 using UnityEditor;
 using UnityEngine;
 using System;
 using System.Reflection;
 
 [CustomPropertyDrawer(typeof(SimpleButtonNewAttribute))]
 public class SimpleButtonNewDrawer : DecoratorDrawer
 {
     //Unity GUI function for Property Drawer
     public override void OnGUI(Rect _Position)
     {
         // First get the attribute
         SimpleButtonNewAttribute tAttribute = attribute as SimpleButtonNewAttribute;
 
         UnityEngine.Object theObject = Selection.activeGameObject.GetComponent(tAttribute.ClassType) as UnityEngine.Object;
 
         if (GUI.Button(_Position, tAttribute.ButtonName))
         {
             //Match found get the function in MethodInfo for Invoke
             //Debug.Log("Found match:  " + TargetObjects[i].GetType() + "   " + tFunction.ClassType);
             MethodInfo tMethod = theObject.GetType().GetMethod(tAttribute.FunctionName);
 
             Debug.Log("Method: " + tMethod + " Object: " + theObject + "   Type : " + theObject.GetType() + "    found Method: " + theObject.GetType().GetMethod(tAttribute.FunctionName));
 
             if (tMethod != null)
             {
                 //Invoke the method if != null Note: It works only of you dont need special parameters! (null)
                 tMethod.Invoke(theObject, null);
             }
         }
     }
 
     public override float GetHeight()
     {
         return base.GetHeight() *2f;
     }
 }

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 TomNCatz · Apr 11, 2020 at 11:08 PM 0
Share

This is a rather reasonable solution and has a lot of potential. One notation I will add is that his only works if the method being called is public.

I rewrote this a bit for my own purposes so that you can specify a validator function as well so that the button only shows when it contextually makes sense.

avatar image
0

Answer by BMayne · Oct 26, 2015 at 03:09 PM

Hey,

The PropertyAttribute is only valid on fields of a class. The whole point of a Property drawers is to override the drawing of a field that is serialized. Since methods are not serialized (that does not even make sense) you can't have a PropertyAttribute on them.

There is another function that you can use which is ContextMenu. This is what Unity did to get around the issue that you are trying to solve.

Cheers,

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 RChrispy · Oct 26, 2015 at 05:07 PM 0
Share

Well the normal Attribute can be used on Clases and methodes:

https://msdn.microsoft.com/en-us/library/aa664613(v=vs.71).aspx

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.$$anonymous$$ethod)]

I will lookup the Context$$anonymous$$enu but I dont understand why the PropertyAttribute of Unity that inherits of System.Attribute can't do the same!

avatar image BMayne RChrispy · Oct 26, 2015 at 05:20 PM 2
Share

Attribute is a System type. You are trying to interact with Unity so you use PropertyAttribute which is like Attribute (it inherits from it) but they have custom logic for it.

Unity draws it's inspector in an abstract way. It has no idea what the class looks like. It tells it to serialize itself and draws the representation.

For each serialized field (SerializedProperty) it checks to see if it has any custom attributes and if it does checks to see if they have property drawers. It it does it draws their drawers.

$$anonymous$$ethods don't get serialized so the inspector does not look at them and would have never even tried to figure out the attribute you have applied to it.

Closing note: Just because you can does not mean it will work.

avatar image Ash-Blue · Aug 17, 2017 at 08:03 PM 0
Share

I don't understand how this answer solves the problem of adding a button via PropertyAttribute. $$anonymous$$aybe I'm missing something???

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

34 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

Related Questions

Select a readonly value from dropdown using PropertyDrawers 0 Answers

Texture2D on Property Drawers. 0 Answers

PropertyDrawer not updating in custom inspector. 0 Answers

What should be handled in the custom inspector version of a script? 1 Answer

Custom Inspector Horiztonal Vector2 and Button Spacing 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