0

By using the ternary operator ?:

perClick  = PlayerPrefs.HasKey("clickpoints") ? PlayerPrefs.GetFloat("clickpoints") : 2.0f;

I want to assign to the "perClick" variable the float stored in the PlayerPref, if the condition evaluates to True, or, if it evaluates to False, I want to set "perClick" to 2. However, if False, I also want to do PlayerPrefs.SetFloat("clickpoints, 2.0f). Is it possible to add more than one statement to the last option?

3
  • You could call a method that does both as long as it returns the right type Commented Jul 31, 2021 at 3:33
  • perClick = PlayerPrefs.GetFloat("clickpoints", 2.0f); Just use the default value version of the function. docs.unity3d.com/ScriptReference/PlayerPrefs.GetFloat.html If you want to force the preferences to have the value call PlayerPrefs.SetFloat("clickpoints, perClick); too. If perClick is a property you could set the preferences whenever it changes in the setter. Commented Jul 31, 2021 at 3:35
  • 1
    Use an if then else construct instead. It will make your code easier to read and won't require you to curse and give up. The two parts of a ternary are expressions not statements. The way they work is var result=someCondition ? valueIfTrue : valueIfFalse;. There's no room there for a statement like an unrelated function calll Commented Jul 31, 2021 at 3:35

1 Answer 1

1

You cannot use the ternary operator to achieve this but you can squeeze the desired effects into one conditional statement:

if (PlayerPrefs.HasKey("clickpoints"))
  perClick = PlayerPrefs.GetFloat("clickpoints");
else
  PlayerPrefs.SetFloat("clickpoints", perClick = 2.0f);

However I cannot stress enough how bad it is to do this, because the logic is obfuscated (easy for even a trained eye to miss important details). Your code should be self documenting where possible, particularly when no extra efficiency can be gained from reducing the number of lines of code (or preferring ?: which is syntactic sugar for if-else most of the time - see Is the conditional operator slow?).

Much better to make your meaning clear...

....
else
{
  perClick = 2.0f;
  PlayerPrefs.SetFloat("clickpoints", perClick);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.