• 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
0
Question by JustinC · Apr 27, 2015 at 04:00 AM ·

System.Reflection.MethodInfo

Hey all, I am trying to create a state machine and found an example of a simple one. I understand most of how it works except for the part that invokes the next method. it is as follows

 public void NextState ()
     {
         string methodName = state.ToString() + "State";
         System.Reflection.Method info = 
             GetType().GetMethod(methodName,
                     system.Reflection.BindingFlags.NonPublic |
                     system.Reflection.BindingFlags.Instance);
 
         startCoroutine((IEnumerator).info.Invoke(thiss, null));
 
     }

My main question is what does System.Reflection.Method and GetType().GetMethod do, and how does it work. I could not find any documentation that made sense to me. Any help is appreciated

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
4
Best Answer

Answer by Bunny83 · Apr 27, 2015 at 04:53 AM

Well, System.Type, GetType(), GetMethod, MethodInfo and those things belong to the Reflection system of .NET / Mono. Reflection allows you to inspect and modify types at runtime. Using reflection to call a method is rather slow compared to a normal method call.

Your code contains a lot syntax errors. It should probably be something like:

 public void NextState ()
 {
     string methodName = state.ToString() + "State";
     System.Reflection.MethodInfo info =
         GetType().GetMethod(methodName,
             system.Reflection.BindingFlags.NonPublic |
             system.Reflection.BindingFlags.Instance);
     StartCoroutine((IEnumerator)info.Invoke(this, null));
 }

To break it down what happens:

  • state is probably an enum value which contains the current state.

  • The enum value is converted into a string and "State" is added to the end. So if there's a state called "Blubb" you will get a string that looks like: "BlubbState".

  • The next long line can be broken up into two parts ...

  • GetType (or this.GetType to be more explicit) returns the System.Type object that describes the type of the class where this method "NextState" belongs. Every type in the .Net / mono framework has a System.Type object that describes that type. Even types like "int" or "bool".

  • GetMethod is a method of the System.Type object and can be used to get a MethodInfo instance for a given method name.

  • MethodInfo is a class that describes a Method of a type. With this instance you can inspect the method signature (parameter, return type, ...) or even call / invoke the method.

  • So this long line simply gets the MethodInfo object for a method called "BlubbState". This method has to exist in this class or GetMethod will return null.

  • In the last line we call Invoke on the MethodInfo object which will invoke that method. Since it's an instance method (a non static method) you need to pass an object on which this method should be called. That's why the first parameter to Invoke is "this". This code requires the BlubbState method to be a coroutine. Since a coroutine will return an IEnumerator object we cast the return value inti IEnumerator and pass it to StartCoroutine to start the coroutine.

That's all. Actually it's quite pointless to use this method since SendMessage or Invoke can do the same in one line. Those will use relfection behind the scenes.

So the method could be simplified to:

 public void NextState ()
 {
     string methodName = state.ToString() + "State";
     SendMessage(methodName);
 }

In general you should avoid Reflection as it breaks almost all OOP rules. Reflection can be the cause of the strangest bugs which usually are impossible. Since everything is based on strings and evaluated at runtime, spelling errors aren't detected by the compiler.

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 JustinC · Apr 27, 2015 at 05:33 AM 0
Share

Thank you very much for the detailed explanation, I love it when people are willing to help a guy out and do not just put "google it". Once again thanks a ton!

avatar image JustinC · Apr 27, 2015 at 06:20 AM 0
Share

One more question, I did as you suggested and replaced that method with yours. With that said the state would not switch to the next state, when I switched it back to the system.reflection.blah.blah it started switching states again, just wondering if you know why?

avatar image Bunny83 · Apr 27, 2015 at 10:12 AM 0
Share

Yes, i'm sorry but i rarely use Invoke / Send$$anonymous$$essage ^^. Unity's Invoke seems to be just a delayed wrapper for a reflection call. The strange thing is while Send$$anonymous$$essage and Invoke do almost the same, Send$$anonymous$$essage is able to start coroutines while Invoke is not. I'll fix my answer.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

20 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

Related Questions

Trying to make Collider Activate with key code 1 Answer

How do I make my player face the direction its moving. 0 Answers

Changing Force of object 1 Answer

Importing Huge Videos into Unity 1 Answer

how to make Enemy Ai aircraft shoot at me 1 Answer


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