Search Unity

Adding New Overloads For Unity Libraries Such as Physics.RayCast()

Discussion in 'Scripting' started by Jonathan-Westfall-8Bits, Sep 24, 2018.

  1. Jonathan-Westfall-8Bits

    Jonathan-Westfall-8Bits

    Joined:
    Sep 17, 2013
    Posts:
    271
    So I was wondering if anyone knew how to add new overloads to methods that are built into Unity. I have never tried to do anything with dll so going in pretty blind here.

    I was wanting to create new methods for Physics2D.Raycast() that I would find some use for.
    For starters I tried importing the DLL using System.Runtime.InteropServices than overloading the Raycast method using
    Public extern static bool.

    Code (CSharp):
    1. using System.Runtime.InteropServices;
    2.  
    3. namespace UnityEngine
    4. {
    5.    
    6.     public class Physics2DExtended : Physics2D
    7.     {
    8.  
    9.         [DllImport("Assets/Plug-ins/UnityEngine.Physics2DModule.dll")]
    10.         public extern static bool Raycast(Vector2 origin, Vector2 direction, out RaycastHit2D hitInfo, float maxDistance);
    11.  
    12.     }
    13. }
    I was able to read the DLL correctly, but I got an error with as much as I looked around couldn't find a nice fix that worked for me. I found several forums that talked about fixes, but none of them worked.

    The error was
    Capture.PNG


    Player Interaction is where I was trying to call the new method I created. I have the dll in the project folder so not sure what to do after trying this.

    Anyone that could help this noob out would be very much loved.
     
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    Fundamentally, you don't. If you want to create your own versions of things, then just make your own class.

    What kind of uses?
     
  3. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    You can write an extension class, that does what you want.
    Code (CSharp):
    1. public static class MyPhysics{
    2.      public static void Raycast2D(...) {
    3.          // Do what you want
    4.          ....
    5.      }
    6. }
    Then call it via MyPhysics.Raycast2D(...);
    No need to hack stuff :)
     
    FernandoHC likes this.