I needed to cast a generic type deriving from UnityEngine.Object
into UnityEngine.AudioClip
, but I was having this error all the time:
Error Message:
error CS0030: Cannot convert type 'T[]' to 'UnityEngine.AudioClip[]'
And I was baffled, cause AudioClip
derives from Object
, so it shouldn't be an issue to cast to it.
So the Example Code 1 below is how my code was when I got the error. Then I solved the error by changing the code to the one in Example Code 2.
So my question is:
Why did a direct cast (ie. using parenthesis) NOT work, but casting using the as
-keyword did?
I want to understand why Example Code 2 works. I've looked at the "Direct casting vs 'as' operator?"-answer, but I don't understand how that would be related to this issue. So any help or explanation as to why this works the way it does would be really appreciated.
Example Code 1: Direct Cast (ie. using Parenthesis)
private void UpdateAudioClipsOnDragAndDrop<T>(T[] draggedObjects) where T : UnityEngine.Object
{
audioClips = (AudioClip[])draggedObjects;
}
Example Code 2: Cast using the "as
"-keyword
private void UpdateAudioClipsOnDragAndDrop<T>(T[] draggedObjects) where T : UnityEngine.Object
{
audioClips = draggedObjects as AudioClip[];
}