Lego
Lego

Reputation: 490

yz Vector3 to Vector2

Simple question, no answer found around the web.

Is there an easy way to cast the Y,Z of a Vector3 into a Vector2 without creating a "new Vector2()"

Something like

Vector3 v = Vector3.one;
Vector2 plan = v.yz;

(All that with C# in Unity3d) Thx

Upvotes: 1

Views: 7374

Answers (2)

Mikeb
Mikeb

Reputation: 6361

No, you can't avoid making a new Vector2 if that's what you want, as it is a different object from Vector2 and they aren't assignable to each other in any way. Kay's extension method would give you the syntax you are looking for, but if you are just concerned about allocating memory / new objects in an Update loop or something, you are out of luck.

If you had complete control over the Vector3 and Vector2 classes, I guess you could make Vector3 inherit from Vector2 and add the x component; then you'd be able to cast a Vector3 to a Vector2 (treating a child class as it's parent class) and only use the y & z components. However, you are likely working in a Unity library that is going to be returning it's own Vector3 classes, and anyway, that inheritance hack would be a dumb idea anyway. Also it would force you to only ever get y&z components; if you wanted z&x, or x&y ... well, you'd be back to new Vector2() again.

Upvotes: 2

Kay
Kay

Reputation: 13146

C# has a pretty cool feature called extension methods. Set up a class VectorExtensions for example and put this code inside:

public static Vector2 YZ (this Vector3 v) {
    return new Vector2 (v.y, v.z);
}

Now you can call from everywhere in your project:

Vector2 v2 = v3.YZ ();

Upvotes: 6

Related Questions