How do I use the numbers from a vector2 array and use them in a vector3?
What I currently have is and change the vector2 components in the editor.
public Vector2[] coordX;
public Vector2[] coordY;
Vector3[] verts = new Vector3[]{
new Vector3 (coordX.x, coordX.y, 0f),
new Vector3 (coordY.x, coordY.y, 0f),
new Vector3 (coordX.x, coordX.y, l),
new Vector3 (coordY.x, coordY.y, l)
};
The errors I get are for all 4 vector3:
Type UnityEngine.Vector2[ ]' does not contain a definition for x’ and no extension method x' of type UnityEngine.Vector2[ ]’ could be found (are you missing a using directive or an assembly reference?)
Type UnityEngine.Vector2[ ]' does not contain a definition for y’ and no extension method y' of type UnityEngine.Vector2[ ]’ could be found (are you missing a using directive or an assembly reference?)
The best overloaded method match for `UnityEngine.Vector3.Vector3(float, float, float)’ has some invalid arguments
Argument #1' cannot convert object’ expression to type `float’
Why you are getting the error:
You are defining an array of Vector2:
and after you are trying to get the x value of your array, which does not exist because it’s an array… You have to target an element inside the array like so:
Vector3 v = new Vector3(coordX[0].x, coordX[0].y, 0);
Are you trying to start from an array of vector2 and create an array of vector3 out of it?
Copy Vector2 array into Vector3 array…
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public Vector2[] startCoord;
public Vector3[] endCoord;
void Start ()
{
endCoord = Vector2ToVector3Array(startCoord);
}
Vector3[] Vector2ToVector3Array(Vector2[] startArray)
{
Vector3[] endArray = new Vector3[startArray.Length];
for(int i = 0; i < startArray.Length; i++)
{
endArray[i] = Vector2ToVector3(startArray[i]);
}
return endArray;
}
Vector3 Vector2ToVector3(Vector2 v)
{
Vector3 v3 = new Vector3(v.x, v.y, 0);
return v3;
}
}
@sluice has the answer for you and you should consider what @TJHeuvel-net is saying as well. But if you still ahve to convert Vector2 to Vector3 a lot in the future, this is where a little syntactic sugar of the extension method may help you.
using UnityEngine;
public static class VectorTools {
public static Vector3 ToVector3(this Vector2 v) {
return new Vector3(v.x, v.y);
}
public static Vector3[] ToVector3Array(this Vector2[] v) {
Vector3[] v3a = new Vector3[v.Length];
for (int i = 0; i < v.Length; i++) {
v3a[i] = v[i].ToVector3();
}
return v3a;
}
}
you can use that code to create the extension method than in the future you can Convert a Vector2 to a Vector3 like this
Yes, Linq will be slightly less efficient. I’m not sure if .ToArray() actually copies to an array or casts to an array. I’d have to check on that. Select is a pretty friendly Linq method. There are some you have to be careful of though, I believe GroupBy is a good example, as with these being value types you’ll actually end up boxing and unboxing.