Soaring Code Soaring Code - 2 months ago 9
C# Question

How to compact if operator for this statement in Unity C#

In "Unity" we often debug to console.

public bool printInConsole;

void Start()
{
if ( printInConsole ) Debug.Log("Starting and printing...");
}


I would like to call this Unity function using the compact ? ternary operator.

How do I write a statement for this in Unity using C#?

Answer

No, there is no way to make a if statement more compact than:

if ( printInConsole ) Debug.Log("Starting and printing...");

A better visual way, as "Rahul" points out, that is more readable is:

if ( printInConsole ) 
   Debug.Log( "Starting and printing..." );

As "Genos" mention, is not correct to use a C# compact ternary operator as for example:

printInConsole ? Debug.Log("Starting and printing...");

Because it needs a second else expression.

It is possible to do it inside the function, but the result is not more compact, simple or readable.:

Debug.Log(printInConsole ? "Running and printing..." : "\n");

"itsme86" and my conventional solution is to create a specific compact function method. In this way, the calling function is more compact.

Mss("Starting and printing..." );

In my case the full Unity code example will be:

public bool printInConsole;

void Start()
{
    Mss("Starting and printing..." );
}

private void Mss(string consoleMessage)
{
    if (printInConsole)
        Debug.Log(consoleMessage + "\n");
}

Another solution is to assign to a keyboard button a custom macro to prints out:

if ( printInConsole ) 
   Debug.Log( "" + "\n");

Please since I'm not English, I pray you to improve my answer.