- Home /
Returning Multiple Variables From a Function
I'm new to unity and trying to use a Vector2 as an index position for a 2D array. I've done a lot of searching but haven't found a solution yet. I tried something like this
int[,] intArray;
Vector2 pos = new Vector2(7, 6);
intArray[vectToInt(pos)] = 3;
int vectToInt(Vector2 i) {
dualInt j;
j.x = Mathf.RoundToInt (i.x);
j.y = Mathf.RoundToInt (i.y);
return j;
}
public struct dualInt {
public int x;
public int y;
}
to return two integers, but that didn't work. How else could I do it in an efficient way, I was using
intArray[Mathf.RoundToInt (vector2.x), Mathf.RoundToInt (vector2.y)] = int;
but I want something simpler.
$$anonymous$$any things:
You cant set array elements in C# outside a method, you can only initialize the entire array.
A bidimensional need 2 values coma separated not a struct.< br> You need initialize the array before use it.
You aren't quite there. You need the comma separated value, and you returned int ins$$anonymous$$d of dual int. Fixing your method:
int[,] intArray;
Vector2 pos = new Vector2(7, 6);
intArray[vectToInt(pos).x, vectToInt(pos).y] = 3;
dualint vectToInt(Vector2 i) {
dualInt j;
j.x = $$anonymous$$athf.RoundToInt (i.x);
j.y = $$anonymous$$athf.RoundToInt (i.y);
return j;
}
public struct dualInt {
public int x;
public int y;
}
Answer by ElijahShadbolt · Oct 17, 2016 at 04:24 AM
I created a struct similar to dualint in james2238's more recent post, which I named int2. It has extension methods for 2D arrays to use the int2 as an index, as well as easy conversion from Vector2's.
Your answer
Follow this Question
Related Questions
Using Vector2 as 2D Array Index 1 Answer
Deriving and angle from two points 1 Answer
Need help with Vector3s and Vector2s 2 Answers
Overload Vector3's operator + 2 Answers
Joystick to turn object 1 Answer