0
\$\begingroup\$

It is my first time integrating Unity ads into my game and my first time encountering the sample code below with the usage of "?" and ":" and wanted to ask how to read the line of code below specifically the way it assigns the _gameId.

public void InitializeAds()
{
    _gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
        ? _iOSGameId
        : _androidGameId;

    Advertisement.Initialize(_gameId, _testMode, this); 
}
\$\endgroup\$
1
  • \$\begingroup\$ When you have questions about programming syntax, it's better to search our general programming sister site StackOverflow. They'll already have answers to common questions like this. Ask here when you need help with topics that are specific to game development, not part of the C# language that's used for all kinds of non-game software too. \$\endgroup\$
    – DMGregory
    Sep 19 at 12:50

1 Answer 1

1
\$\begingroup\$

This code uses the C# ternary operator.

This construct consists of three parts. A condition and two values.

<condition> ? <value_true> : <value_false>

When the condition is true, this construct returns the first value. When the condition is false, it returns the second value.

So what happens here is that the condition Application.platform == RuntimePlatform.IPhonePlayer is being evaluated. When it is true, then _gameId gets set to _iOSGameId. When it is false, then _gameId gets set to _androidGameId.

If you feel uncomfortable with ternary expression, then you could also write the whole method as this:

public void InitializeAds()
{
    if(Application.platform == RuntimePlatform.IPhonePlayer) 
    {
        _gameId = _iOSGameId;
    } 
    else 
    {
        _gameId = _androidGameId;
    }

    Advertisement.Initialize(_gameId, _testMode, this); 
}

What's immediately visible here is that any platform except iPhone is assumed to be Android. I am not familiar with the Unity ingame advertisement API, but this has some obvious code smell to me.

\$\endgroup\$
1
  • \$\begingroup\$ Now that makes sense. I'm used to using the structure you provided as the alternative and much readable to me. Thanks for this! \$\endgroup\$ Sep 19 at 8:42

Not the answer you're looking for? Browse other questions tagged .