Ternary Operator

Tutorial

·

intermediate

·

+10XP

·

5 mins

·

(71)

Unity Technologies

Ternary Operator

How to utilize the Ternary Operator to build simple, shorthand IF-ELSE logical conditions.

Languages available:

1. Overview

In this short tutorial you will learn about a piece of syntax that allows if statements to be slightly tidier: the ternary conditional operator. It works like a simple if statement but can be written on a single line.


2. Before you begin

This tutorial is part of Intermediate Scripting, a collection of basic introductions to a wide range of different programming concepts. If you want a guided introductory learning experience, try the Create with Code course or the full Junior Programmer pathway.


3. Syntax

The operator has the following syntax:


[@portabletext/react] Unknown block type "code", specify a component for it in the `components.types` prop

Each of the parts of the operator only allow for a single statement which is evaluated only if the condition is met or not met respectively. Here is an example:


[@portabletext/react] Unknown block type "code", specify a component for it in the `components.types` prop

In this example, the isPlayerGrounded bool is checked. If the player is grounded then groundSpeed will be returned by the conditional ternary operator and subsequently assigned to the currentSpeed. Otherwise if the player is not grounded then airborneSpeed will be returned and assigned to the currentSpeed.


4. Summary

This was a very short tutorial and deliberately so. Use of the conditional ternary operator is fine for simple cases and being able to identify it in code written by someone else is important. However overuse can make code more difficult to read so always consider who is going to need to read your code when considering using it.


Complete this tutorial