- Home /
C# Convert Vector3[] to Vector2[]
I tried looking for a specific Vector3 function that converts a Vector3[] to a Vector2[] but I wasn't able to find anything named like toVector2() . Is there actually a function that converts a Vector3[] to a Vector2[] or will I need to create one from scratch?
Answer by NeverHopeless · Aug 24, 2015 at 07:55 AM
Perhaps using extension methods in combination with Array.ConvertAll will be more close to your needs:
Add this extension to your script:
public static class MyVector3Extension
{
public static Vector2[] toVector2Array (this Vector3[] v3)
{
return System.Array.ConvertAll<Vector3, Vector2> (v3, getV3fromV2);
}
public static Vector2 getV3fromV2 (Vector3 v3)
{
return new Vector2 (v3.x, v3.y);
}
}
and use it like:
Vector2[] v2 = v3.toVector2Array ();
Here is an example enclosed:
using UnityEngine;
using System.Collections;
public class TestVectorConvert : MonoBehaviour
{
// Use this for initialization
void Start ()
{
Vector3[] v3 = new Vector3[5];
for (int i = 0; i < 5; i++) {
v3 [i] = new Vector3 (0.5f, 0.4f, 1.0f);
}
Vector2[] v2 = v3.toVector2 ();
for (int i = 0; i < 5; i++) {
Debug.Log (v2 [i].ToString ());
}
}
// Update is called once per frame
void Update ()
{
}
}
public static class MyVector3Extension
{
public static Vector2[] toVector2 (this Vector3[] v3)
{
return System.Array.ConvertAll<Vector3, Vector2> (v3, getV3fromV2);
}
public static Vector2 getV3fromV2 (Vector3 v3)
{
return new Vector2 (v3.x, v3.y);
}
}
Answer by fafase · Aug 24, 2015 at 03:46 AM
There probably isn't any so you can do you own:
Vector2[] ConvertArray(Vector3[] v3){
Vector2 [] v2 = new Vector2[v3.Length];
for(int i = 0; i < v3.Length; i++){
Vector3 tempV3 = v3[i];
v2[i] = new Vector2(tempV3.x, tempV3.y);
}
return v2;
}
Answer by gabriel-diquinzio · Apr 24 at 01:36 AM
the one liner way using linq library.
using System.Linq;
List<Vector3> v3positions = new List<Vector3>();
List<Vector2> v2Positions => v3positions.Select((v3) => (Vector2)v3).ToList();
Your answer
Follow this Question
Related Questions
C#-XMLSerialize a Struct with Vector3 Array in it 2 Answers
Setting position of a transform? 2 Answers
Get a position relative to a gameobject 0 Answers