Reputation: 53
I would like to make some code for a game a little more compact. Here is the original.
if (killPosX != 0) // float x position you would like the object to be destroyed at
{
killX = true; // automatically makes the value of killX true
}
if (killPosY != 0) // float y position you would like the object to be destroyed at
{
killY = true; // automatically makes the value of killY true
}
if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
killT = true; // automatically makes the value of killT true
}
And I want to turn it into something like this:
if ([killPosX, killPosY, killPosT] != 0)
{
[killPosX, killPosY, killPosT] = true;
}
How would I do that?
Upvotes: 0
Views: 95
Reputation: 11
I can't think of a way to do it as you suggest but it might be a little neater and more compact to use a variation of the approach hellium suggested:
public void fnc(ref bool t1, float t2) { t1 |= !Mathf.Approximately( t2, 0 ); }
fnc(ref KillX, KillPosX);
fnc(ref KillY, KillPosY);
fnc(ref KillT, KillPosT);
You could of course wrap it in a method which uses arrays as parameters but unless you need a generic way to do this for variable sized arrays, the setup cost is bulkier than just using discrete calls.
Upvotes: 0
Reputation: 37020
I'm not sure if this applies to what you're working on (and there may be a better way in Unity), but it seems to me that one way to do it would be to make the KillN
properties calculated on the value of their corresponding KillPosN
property:
public class SomeClass
{
public float KillPosX { get; set; }
public float KillPosY { get; set; }
public float KillPosT { get; set; }
// Values are based on the related property values and cannot be set directly
public bool KillX => !IsRoughlyZero(KillPosX);
public bool KillY => !IsRoughlyZero(KillPosY);
public bool KillT => !IsRoughlyZero(KillPosT);
private static bool IsRoughlyZero(float input)
{
// Use a tolerance for comparing floating point numbers to 0
return Math.Abs(input) < .0000001;
}
}
Upvotes: 0
Reputation: 7346
if (killPosX != 0)
{
killX = true;
}
Could be translated as follow
killX = (killPosX != 0) ? true : killX;
Or more simply
killX |= killPosX != 0;
if (killPosX != 0)
{
killX = true;
}
else
{
killX = false;
}
Could be translated as follow
killX = (killPosX != 0) ? true : false;
Or more simply
killX = killPosX != 0;
But since comparing floats using ==
or !=
is not advised, I would go for:
killX |= !Mathf.Approximately( killPosX, 0 );
killY |= !Mathf.Approximately( killPosY, 0 );
killT |= !Mathf.Approximately( killPosT, 0 );
AFAIK, there is no built-in syntax similar to what you wrote in order to achieve what you want.
Upvotes: 4