Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Store operation in a variable?

Discussion in 'Scripting' started by rothpletz5, Jul 22, 2021.

  1. rothpletz5

    rothpletz5

    Joined:
    Dec 2, 2020
    Posts:
    27
    Greetings,

    I have a function that contains a long switch statement. Depending on the string that is input into it, it will multiply a different variable by a value. I have a second function almost identical to the first, except it divides the variable by the value, in order to cancel out the first function (after a certain amount of time.)

    Is there any way to combine the two, in order to prevent redundant code, such as storing an operation as a variable? I know this is dumb, but this is what I have in mind:

    Code (CSharp):
    1. void myFunction(string condition, float value, Operation op){
    2.      switch(condition){
    3.           case"Condition1":
    4.               varOne op= value;
    5.               break;
    6.            case"Condition2":
    7.               varTwo op= value;
    8.               break;
    9.     }
    10. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    You're looking for delegates. A delegate is basically a reference to a function that can be passed around as a variable - it can be stored, passed as a parameter, etc.

    You first need to define the delegate's signature, which looks like a regular function definition, but with the word "delegate" and no function body:
    Code (csharp):
    1. public delegate bool OperationDelegate(float x);
    Then you can use OperationDelegate as the type of the variable (which is the function being pointed to):
    Code (csharp):
    1. void myFunction(float value, OperationDelegate operation) {
    2. bool returnedValue = operation(value);
    3. }
    Now you have two ways of calling this. You can do it with a reference to a regular function:
    Code (csharp):
    1. public bool IsBig(float x) {
    2. return x > 5f;
    3.  
    4. myFunction(2f, IsBig);
    Or you can define it inline, which is called a "lambda function":
    Code (csharp):
    1. myFunction(2f, (x) => {
    2. return x > 5f;
    3. });
    If needed, I could give more helpful examples if you could describe what your actual goal is here.
     
    Kurt-Dekker likes this.
  3. rothpletz5

    rothpletz5

    Joined:
    Dec 2, 2020
    Posts:
    27
    Thank you! My goal is equipping/unequipping the players armor and weapons. The function is intended to increase a value when equipped (ex +15% defense=
    defense*=1.15
    ) and return it to its regular value when unequipped (ex -15% defense=
    defense/=1.15
    ).
    Essentially, I'd like to do this using the same function to avoid repetitive code.