1

It it possible to have a function that blindly handles dynamic method names and dynamic parameters?

I'm using Unity and C#. I want the drawing of a Gizmo to persist for a little while after an object is removed from the scene (destroyed) so I want to pass the drawing responsibilities to another object dynamically.

For example, I would like to be able to do this:

GizmoManager.RunThisMethod(Gizmos.DrawSphere (Vector3.zero, 1f));
GizmoManager.RunThisMethod(Gizmos.DrawWireMesh (myMesh));

As you can see the method being called and the parameter count varies. Is there a way to accomplish my goal without writing a very elaborate wrapper for each gizmo type? (There are 11.) (Side goal: I want to also add my own argument to say how long the manager should keep drawing the gizmo, but this is optional.)

1 Answers1

5

I would recommend turning the call into a lambda. This will allow GizmoManager to invoke it as many times as needed.

class GizmoManager
{
  void RunThisMethod(Action a)
  {
    // To draw the Gizmo at some point
    a();
  }
  // You can also pass other parameters before or after the lambda
  void RunThisMethod(Action a, TimeSpan duration)
  {
    // ...
  }
}

// Make the drawing actions lambdas
GizmoManager.RunThisMethod(() => Gizmos.DrawSphere(Vector3.zero, 1f));
GizmoManager.RunThisMethod(() => Gizmos.DrawWireMesh(myMesh));

// You could also draw multiple if needed:
GizmoManager.RunThisMethod(() => {
    Gizmos.DrawSphere(Vector3.zero, 1f);
    Gizmos.DrawWireMesh(myMesh);
});
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98