Hey guys,
I need to do something like the following
function Main()
{
Vector3 vector = arrayOfVerts[0];
calculationFunc(vector.xy);
}
function calculationFunc(Vector2 theVector2)
{
//Use only those components to calculate something
}
The problem is at the vector.xy. Unlike in GLSL, you can’t access components like that (apparently). What would be the most performance-wise way of doing this?
I just want to sum up some ways:
// our vector3
var vec = new Vector3(1,2,3);
// #1 The usual way
var tmp = new Vector2(vec.x, vec.z);
// #2 Your way
var tmp = getAxis(vec, Axis.x, Axis.z);
// #3 My way ;)
var tmp = vec.xz();
My way requires you to add this extension class to your Standard Assets folder:
// Vector3Extensions.cs
// C#
using UnityEngine;
public static class Vector3Extensions
{
public static Vector2 xy(this Vector3 aVector)
{
return new Vector2(aVector.x,aVector.y);
}
public static Vector2 xz(this Vector3 aVector)
{
return new Vector2(aVector.x,aVector.z);
}
public static Vector2 yz(this Vector3 aVector)
{
return new Vector2(aVector.y,aVector.z);
}
public static Vector2 yx(this Vector3 aVector)
{
return new Vector2(aVector.y,aVector.x);
}
public static Vector2 zx(this Vector3 aVector)
{
return new Vector2(aVector.z,aVector.x);
}
public static Vector2 zy(this Vector3 aVector)
{
return new Vector2(aVector.z,aVector.y);
}
}
It will also work from UnityScript, but Monodevelop doesn’t seem to provide intellisens for the extension methods, however it works 
edit
Just to have it complete:
- 1 is the fastest and most efficient way
- 2 is the most inefficient way of the 3 because it uses the indexer of vector3 two times and involves a function call
- 3 in the middle since it also requires an additional function call but it has the shortest syntax.
EDIT: See accepted answer and explanations that go with it, much better than mine.
Future reference for anyone coming across this in the future. This is what I did. Vector3s’ components can be accessed like an array.
Vector3 bobTheVector = new Vector3(1, 2, 3);
float oneAxis = bobTheVector[0];
Here’s the way I implemented it.
enum Axis : int {x = 0, y = 1, z = 2}
function getAxis(Vector3 theVector, int a, int b)
{
return Vector2(theVector[a], theVector**);**
}
The enum is just incase you want to do something like Axis.x instead of remembering that 0 is the x axis.
getAxis(new Vector3(1, 2, 3), Axis.x, Axis.z);