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?

RicardoP
  • 187
  • 8
  • `perClick = PlayerPrefs.GetFloat("clickpoints", 2.0f);` Just use the default value version of the function. https://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. – Retired Ninja Jul 31 '21 at 03: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 – Flydog57 Jul 31 '21 at 03:35
  • You could call a method that does both as long as it returns the right type – DP3PO Jul 31 '21 at 03:33

1 Answers1

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);
}
AlanK
  • 1,827
  • 13
  • 16