Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
4
Question by MapuHoB · Feb 15, 2015 at 01:20 PM · c#reflection

invoke method with reflection C#

 using UnityEngine;
 using System.Collections;
 using System;
 using System.Reflection;
 
 public class blblb : MonoBehaviour
 {
 
     void Start()
     {
         Type thisType = this.GetType();
         MethodInfo theMethod = thisType.GetMethod("bla");
         theMethod.Invoke(this, null);
     }
 
     private void bla()
     {
         Debug.Log("enters");
     }
 }

NullReferenceException: Object reference not set to an instance of an object blblb.Start () (at Assets/blblb.cs:13)

What am I doing wrong to get this error?

P.S I know there's Invoke method in unity. I need to know how to use the reflection way.

Comment
Add comment · Show 2
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 meat5000 ♦ · Feb 15, 2015 at 03:42 PM 0
Share

"this" is a keyword and can not be used as the name of a function. You probably need to read the Scripting API to see how to use Invoke.

Invoke wants the name of a method as a String and the time before it is invoked.

 Invoke("$$anonymous$$y$$anonymous$$ethod", 0);

This is basically the same as what awplays49 said.

avatar image fafase · Feb 15, 2015 at 04:10 PM 1
Share

The first parameter is the object holding the method instance.

3 Replies

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

Answer by fafase · Feb 15, 2015 at 04:19 PM

This is an example on how to get instance methods. It works for me so there is no reason it should break for you.

 private Action myAction = ()=>{};
 
 void Start()
 {
    System.Type ourType = this.GetType(); 
 
    MethodInfo mi= ourType.GetMethod("MyMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
         
    if (mi!= null){
        myAction = (Action)Delegate.CreateDelegate(typeof(Action), this, mi);
    }
 } 

then you can call myAction(); like any other methods.

This has the advantage of allowing sub class to contain methods or not just like Unity does for Update/LateUpdate or other events. Your top class may contain all the checks and the sub class just implements or not.

Comment
Add comment · Show 7 · 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 ByteSheep · Feb 15, 2015 at 04:35 PM 0
Share

So when you inherit from $$anonymous$$onoBehaviour does that class use Actions to call the Update method (etc) in your child class?

avatar image fafase · Feb 15, 2015 at 04:50 PM 0
Share

I would assume that each mb has a bunch of private actions that are called each frame from the engine. once in the constructor a similar approach to the one I show could be used, hence the slow process of instantiation vs pooling. Reflection is used for sure, how exactly I cannot say

avatar image MapuHoB · Feb 15, 2015 at 07:50 PM 0
Share

@fafase Thank you, first for the explanation. I've got a few questions though.

This has the advantage of allowing sub class to contain methods

Didn't quite understand what did you mean by this.(most likely it's totaly understandable, it's just me sometimes, being unable to get the sense of things from the first glance)

Your top class may contain all the checks and the sub class just implements or not

Isn't this totaly possible with virtual methods and props, like protected virtual bool CheckSmth() and the sub class can choose whether to implement it or not?

http://prntscr.com/65j57f - I saw what they say here for .Instance. But still, as far as I understood it specifies that it should search for members also in the current class. So my question is: System.Type ourType = this.GetType(); isn't here the place we specify the instance(class) where to search at for the given member?

Anyway, very grateful for your answer. I think I learnt much from it!

avatar image fafase · Feb 16, 2015 at 04:53 AM 0
Share

Indeed it is possible to perform the same action with inheritance. This is what XNA framework was doing.

It is just a matter of how you want it to be done. Reflection may be faster (to be confirmed) while polymorphism requries more typing (override keyword...big deal) and has the benefit of autocompletion (the compiler knows the method from parent class while in reflection, no way it can know about it.).

Your call.

avatar image MapuHoB · Feb 16, 2015 at 04:59 AM 0
Share

I understand. Anyway am I doing anything wrong or it's just impossible to call a static methods with the myAction var(I added BindingFlags.Static) but still doesn't work.

Show more comments
avatar image
4

Answer by ByteSheep · Feb 15, 2015 at 03:38 PM

msdn documentation on GetMethod().

"Searches for the public method with the specified name."

Simply make your bla method public ;)

Note: The easiest way to debug this kind of stuff is to use Debug.Log() statements.

 void Start ()
 {
     Type thisType = this.GetType();
 
     Debug.Log ("Type: " + thisType);
 
     MethodInfo theMethod = thisType.GetMethod("bla");
 
     Debug.Log ("MethodInfo: " + theMethod);
 
     theMethod.Invoke(this, null);
 }

theMethod variable is null, since the bla method is private and cannot be found (hence the NullReferenceException).

Comment
Add comment · Show 4 · 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 meat5000 ♦ · Feb 15, 2015 at 03:43 PM 0
Share

I'm guessing this is a 'slow' operation?

avatar image fafase · Feb 15, 2015 at 04:12 PM 2
Share

You can access private methods with

  $$anonymous$$ethodInfo mi= type.Get$$anonymous$$ethod("$$anonymous$$ethodName", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
avatar image ByteSheep · Feb 15, 2015 at 04:17 PM 0
Share

This stackoverflow post covers the cost of reflection quite nicely. Unity's Invoke and Send$$anonymous$$essage methods also use reflection and whydoidoit posted a good answer on it here.

Edit: Thanks for the extra info on accessing private methods fafase :D

avatar image MapuHoB · Feb 15, 2015 at 07:53 PM 0
Share

@merry_christmas Thanks for the time spent on my problem! +1, your answer definatelly helped me a lot, but still fafase's one is a little bit more satisfying + the comments he wrote.

avatar image
1

Answer by awplays49 · Feb 15, 2015 at 02:23 PM

Well first of all, don't type "this", because thats just going to cause errors…

Change your code to:

Invoke ("YourFunction", 0);

assuming the name of your function is YourFunction.

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 MapuHoB · Feb 15, 2015 at 02:28 PM 0
Share

Come on man, please read the whole question, especially the P.S

avatar image awplays49 · Feb 15, 2015 at 02:37 PM 0
Share

You need to be more clear.

avatar image fafase · Feb 15, 2015 at 04:14 PM 1
Share

He is simply telling you to read the P.S of the question. That is he is not using Invoke from $$anonymous$$onoBehaviour but nvoke from .NET which takes Object as first parameter.

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

22 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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Why are the reflected bullets in my 2D game acting strange? 1 Answer

Renderer on object disabled after level reload 1 Answer

How do I orient my glass reflection properly? 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