-3

Hi i'm just learning unity and my problem is this code below is working good right now but it seems like can be written shorter can you help me about that?

    if (isboosted)
    {
        speed = boostSpeed;
    }
    if (!isboosted)
    {
        speed = normalSpeed;
    }

3 Answers3

1

speed = isboosted ? boostSpeed : normalSpeed;

Although it's up to you if you find this format more readable.

I'd also suggest

if (isBoosted)
{
    speed = boostSpeed;
}
else
{
    speed = normalSpeed;
}

is clearer than your original code and possibly easier to follow if you're not used to the ? : syntax.

Sean Reid
  • 911
  • 9
  • 19
  • What Sean shows you here in the first line is called an inline if. You probably want to avoid using it with bigger conditions as it can be hard to read, but it's perfectly suited for cases like this. The syntax works the following: condition ? returned when true : returned when false – 66Gramms Dec 08 '21 at 15:57
  • 3
    @66Gramms it is actually called [ternary conditional operator](https://learn.microsoft.com/dotnet/csharp/language-reference/operators/conditional-operator) ;) – derHugo Dec 08 '21 at 15:58
  • Oh thank you, that is new for me. I've always just heard it refered to as an inline if. I've learnt something today :) – 66Gramms Dec 08 '21 at 15:59
  • Thanks everyone for helps it's worked. – Baran Arslan Dec 08 '21 at 16:05
0

You can use an else statement. The block of an If will run if it's condition evaluates to true. An else block connected to an if only runs when the if's condition was false, resulting in that block of code not executing.

Your code would look like this:

if (isboosted)
{
    speed = boostSpeed;
}
else
{
    speed = normalSpeed;
}

Important thing to note, you can only use else statements after either an if or else if

66Gramms
  • 769
  • 7
  • 23
0

//assuming isboosted is a boolean type

if (isboosted)
    speed = boostSpeed;
else
    speed = normalSpeed;

//or if you like the braces, they are only needed if your if statement actions have more then one line of code

if (isboosted)
{
    speed = boostSpeed;
}
else
{
    speed = normalSpeed;
}