I'm trying to follow a tutorial, but it's in Spanish, I've come across the following bit of code : Code (CSharp): vectorFixed.x = vectorFixed.x == highestValue ? 1 : vectorFixed.x; Not sure I understand it fully though, I've found out the ? operand is a shorthand way of writing the IF statement, so my basic understanding of the same code is : Code (CSharp): if (vectorFixed.x == highestValue) { vectorFixed.x = 1; } else { vectorFixed.x = vectorFixed.x; } So, am I right in my understanding, or completely wrong here ?
You are right. And I would argue it's a really bad piece of code because: 1) it does a float comparison 2) it's not very readable, especially as to what its intent is 3) it's performing a set of itself for no real reason other than to use the ? operator This code could have easily been: Code (csharp): if (vectorFixed.x == highestValue) vectorFixed.x = 1f; Sure, it still has a float comparison, but at least it's readable and doesn't do an unnecessary set in the false case. Also... what is the context of this code? This could probably be streamlined even more depending on how 'highestValue' is calculated. Basically if I knew what the author was attempting to accomplish based on context, this could be refactored.
Wow @lordofduct That was a super quick response! Yes, I agree, Visual Studio has already warned me about the floating point comparison, but I can fix that using the MathF.Approximately function. Excellent, thanks for the information, the script itself is for an off screen object indicator.
Just wanna dd that the a ? b : c operator is actually called the ternary operator. I actually don't recommend using it, as @lordofduct pointed out above. Lord's if statement example is much easier to read and directly describes itself. Using the ternary operator is fine if everything is real simple, such as converting a bool to an int, but beyond that just use an if statement and you (and everybody who has to read your code) will thank you. And this is an example of what I mean by converting and complexity: Code (csharp): bool MyBool; int MyInt; // ... elided code here initializes one or the other of the above // bool to int MyInt = MyBool ? 1 : 0; // int to bool (even this is messy, and I believe the parentheses // are required, so I don't recommend it) MyBool = (MyInt == 0) ? false : true;