Soaring Lines Soaring Lines - 1 year ago 104
C# Question

How to use compact if operator for this statement in Unity c#

public bool printInConsole;

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

I want to call a Unity function using the compact ? ternary operator.

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

Answer Source

TLDR Use the if:

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

The syntax of a ternary expression in C# is as follows:

condition ? first_expression : second_expression;

In your scenario the ternary operator cannot be used since:

  1. It requires two expressions: one in case the condition is true(first_expression) and another one for false(second_expression).
  2. Ternary operator expressions must return a value, and Debug.Log() returns void.

You could invent some crazy way for fitting your logic in a ternary operator, like wrapping the Debug.log() call in an Action delegate, but that would be waste, since the whole point of a ternary operator is to make your code simpler...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download