Sunday, October 2, 2022
HomeGame Developmentunity - How to examine if a Vector3 or Quaternion are unassigned?

unity – How to examine if a Vector3 or Quaternion are unassigned?


If a struct kind has not been given any explicit worth, it would normally default to a particular worth helpfully known as default. (Though it is doable the file loading code you utilize does one thing completely different — you have not proven us, so I’m assuming it is following commonplace C# conference).

The members of default will every maintain the worth similar to the default of their respective varieties: 0 for numbers, false for booleans, null for reference varieties, and so forth.

So you’ll be able to examine:

if (!place.Equals(default)) {/*...*/}

if (rotation != default) {/*...*/}

For a Vector3, the default worth is identical as Vector3.zero, ie. (0, 0, 0), simply much less typing, and a bit extra specific that you simply’re checking if it is a default worth not in search of a deliberately-set worth of zero.

But that highlights a little bit of a difficulty with this code: it will not distinguish between loading an merchandise for which no place was set, versus loading an merchandise that was set to (0, 0, 0) intentionally.

If that distinction is vital on your loading logic, then as others have urged, you might need to change the declaration of your variable to:

[SerializeField]
Vector3? place;

This makes it a “nullable” struct — it is nonetheless a worth kind, nevertheless it beneficial properties an additional flag that tracks whether or not a worth has been set.

You can examine this with:

if (!place.HasValue) {/*...*/}

or, for comfort, place == null interprets to this for nullable varieties.

Then, to entry the Vector3 contents, you’d write place.Value.

You’ll notice that I used the .Equals() technique as a substitute of == above. That’s as a result of the equality operator for Vector3 has a built-in tolerance, so a vector very near zero however not really zero will return true for those who examine it to a zero vector with ==. The .Equals() technique solely returns true for an actual match.

For quaternions, you have got a considerably simpler time, in that any legitimate quaternion could have a non-zero worth. ie. Quaternion.Dot(rotation, rotation) must be near 1.0 — even for Quaternion.identification, which is (0, 0, 0, 1) (in x, y, z, w order).

So for those who ever learn an all-zero quaternion (like default), you’ll be able to make certain that was not a intentionally set worth, and must be overridden.

The distinction between an all-zero quaternion and a sound one is far bigger than the tolerance used within the == operator, so you do not strictly want the .Equals() technique on this case.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments