Sunday, October 2, 2022
HomeGame Developmentunity - Tips on how to examine if a Vector3 or Quaternion...

unity – Tips on how to examine if a Vector3 or Quaternion are unassigned?


If a struct sort has not been given any specific worth, it is going to often default to a particular worth helpfully known as default. (Although it is attainable the file loading code you employ does one thing totally different — you have not proven us, so I am assuming it is following commonplace C# conference).

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

So you possibly can 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 express that you just’re checking if it is a default worth not searching for a deliberately-set worth of zero.

However that highlights a little bit of a problem 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 necessary in your loading logic, then as others have recommended, you might need to change the declaration of your variable to:

[SerializeField]
Vector3? place;

This makes it a “nullable” struct — it is nonetheless a price sort, however it good points an additional flag that tracks whether or not a price has been set.

You possibly 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.Worth.

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

For quaternions, you might have a considerably simpler time, in that any legitimate quaternion may have a non-zero worth. ie. Quaternion.Dot(rotation, rotation) needs to 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 possibly can ensure that was not a intentionally set worth, and must be overridden.

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments