Search Unity

Passing a function as a parameter

Discussion in 'Scripting' started by April, Nov 2, 2010.

  1. April

    April

    Joined:
    Dec 14, 2009
    Posts:
    62
    Hi, is there a way to implement the following code in c#? how?
    var x = 0.0;
    var pos = Rect(0, 0, 100, 100);
    function add(a, b) {
    x = a + b;
    }

    function multiply(a,b) {
    x = a * b;
    }

    function callOperation(a, b, func, buttonName) {
    if (GUI.Button(pos, buttonName)) {
    func(a,b);
    }
    }

    function OnGUI() {
    callOperation(1,2, add, "Add");
    callOperation(1,2, multiply, "Multiply");
    }
     
  2. laurie

    laurie

    Joined:
    Aug 31, 2009
    Posts:
    638
    Yes, using delegates. Declare a delegate with a signature matching your 'operation' functions, then use that as the type for the function argument in the callOperation() function.
     
  3. April

    April

    Joined:
    Dec 14, 2009
    Posts:
    62
    hi, laurie. im quite a newbie to c#. can u give me a sample code for delegates? thanks a lot.
     
  4. Chris-Sinclair

    Chris-Sinclair

    Joined:
    Jun 14, 2010
    Posts:
    1,326