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.

Dynamic Parameter Overloading?

Discussion in 'Scripting' started by WhipJr, Aug 12, 2021.

  1. WhipJr

    WhipJr

    Joined:
    Aug 3, 2011
    Posts:
    125
    Given the code below, is it possible to allow the InitializeText() in the start function to ignore the int parameter since it has a default value set, without writing another method overload?

    Code (CSharp):
    1. private void OnEnable()
    2.     {
    3.         InitializeText("Hello World");
    4.     }
    5.     void InitializeText(int id = -1, string customText = "")
    6.     {
    7.         GRTextBox.SetActive(true);
    8.         textLabel.text = customText != "" ? customText : GRText[id == -1 ? textID : id]; //is id still -1? if yes, display the text with matching ID, if not then use id as the text id instead.
    9.         StartCoroutine(hideDisplay());
    10.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    31,223
    Yessir! Named params:

    Code (csharp):
    1. InitializeText( customText: "Hello World");
     
    WhipJr, Bunny83 and Munchy2007 like this.
  3. WhipJr

    WhipJr

    Joined:
    Aug 3, 2011
    Posts:
    125
    Thank you so much!! I knew there had to be a way
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    31,223
    You're welcome!

    May I offer you a point of style / convention? I find this line to be extraordinarily hard to read:

    I would execute the logic to decide the ultimate
    id
    as a traditional if statement, then do the ultimate text decision as a second if statement, assigning results to well-named temporary variables, and finally assign the result to the textLabel.

    Not only that it but the above code only handles customText being blank (empty string) but not null, which are generally two things most people would expect to behave the same.

    There is a test called
    String.IsNullOrEmpty()
    that does this:

    https://docs.microsoft.com/en-us/dotnet/api/system.string.isnullorempty?view=net-5.0
     
  5. WhipJr

    WhipJr

    Joined:
    Aug 3, 2011
    Posts:
    125
    Yeah, that was mostly a test to see if you could do nested shorthand if statements. lol. I only recently began using them and was just messing around with them to see if I could follow the logic without writing it all out. additionally, I'm trying to use them wherever I can so I remember the syntax.

    I didn't know about the IsNullOrEmpty Function of Strings so that is going to be very useful and I will be using that in those conditionals in just a few moments! Thank you again :)
     
    Kurt-Dekker likes this.