- Home /
I can't see a reason for this Array.Reverse() error
I'm trying to reverse the array of pixel information, but the Reverse() command gives a runtime error that it "Cannot cast from source type to destination type." but they're both Color arrays! What's going on?
var texture : Texture2D;
function Start () {
var test : Color[] = texture.GetPixels();
var test2 : Color[] = test.Reverse();
}
Answer by Essential · Jan 20, 2014 at 07:48 PM
WOW. So after exhaustive testing I discovered Reverse() doesn't actually return an array, it returns an IENumerable! Crazy! It's fixed by converting to an array after reversing…
var test2 = test.Reverse().ToArray();
Answer by JoaoOliveira · Jan 20, 2014 at 06:41 PM
Reverse returns void, the change is applied directly to the array (in this case, "test").
If you don't need "test" for anything else, you can simply replace line 5 with:
test.Reverse();
If you do need it, you should make a copy of "test" before applying the Reverse method.
Thanks for the reply but this doesn't work from what I can see. Just adding it onto the end doesn't reverse it, however it does return a reversed array. It works in the below int array example, but not for the Color array… Unless I'm missing something?
var test = [0,1,2,3,4];
var test2 = test.Reverse();
for (var x in test2)
Debug.Log( x );
Answer by Uncasid · Jan 20, 2014 at 06:48 PM
I think you are supposed to use it like this:
System.Array.Reverse(test);
I don't think you need to assign it to another variable.
That is for C# Arrays.
I believe @Essential is using the Javascript-only one.
Yes I wasn't questioning that, "C# Arrays" (maybe there is a better name for them...) can be used when coding in C# or Javascript in Unity.
What I meant is that @Essential seems to be using the Javascript version, as indicated by the use of "test.Reverse()" (which would be a compilation error using "C# arrays").
Yeah, I realized that, which is why I removed my comment, haha