Search Unity

C# extension methods on GameObject?

Discussion in 'Scripting' started by ecc83, May 24, 2013.

  1. ecc83

    ecc83

    Joined:
    Nov 23, 2012
    Posts:
    32
    I'm trying to extend GameObject with C# extension methods, for example:

    Code (csharp):
    1.  
    2. using ExtensionMethods;
    3.  
    4. GameObject foo = new GameObject("foo");
    5. foo.SendMessage("test");
    6.  
    7. // elsewhere
    8. namespace ExtensionMethods
    9. {
    10.     internal static class ExtendGameObject
    11.     {
    12.         public static void SendMessage(this GameObject go, string methodName)
    13.         {
    14.             Debug.Log(methodName);
    15.         }
    16.     }
    17. }
    18.  
    The above code won't work - the regular method is called. If I change the two instances of "SendMessage" to "SendMessageEx" then it works fine - my method is called.

    What am I doing wrong?
     
  2. SinisterMephisto

    SinisterMephisto

    Joined:
    Feb 18, 2011
    Posts:
    179
    Because send message is an existing function.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class example : MonoBehaviour {
    6.     void ApplyDamage(float damage) {
    7.         print(damage);
    8.     }
    9.     void Example() {
    10.         gameObject.SendMessage("ApplyDamage", 5.0F);
    11.     }
    12. }
    13.  
     
  3. ecc83

    ecc83

    Joined:
    Nov 23, 2012
    Posts:
    32
    Ah, what I'm doing is misunderstanding extension methods!

    You can't override, existing methods with same name always hide the extension method.

    edit - @Sinister, thanks