I use a script to differentiate states of sound and atmosphere without mixing
The problem:
Audioclip ; not add new elements as “Array.add” if allowed (or not as it is).
when we take the audio clip at random, or just take a specific array audio clip, an error occurs and unity3d reports:
- WARNING: Implicit downcast from ‘Object’ to ‘UnityEngine.AudioClip’.
- InvalidCastException: Cannot cast from source type to destination type.
Now the script
#pragma strict
var sound :Music[];
var NumX :int;
var NumY :int;
var AudioSor :AudioSource;
var Min :int = 2;
var Max :int = -2;
function Awake(){
for (var A:int=0;A<sound.length;A++){
if (Max < sound[A].track){Max = sound[A].track;}
if (Min > sound[A].track){Min = sound[A].track;}
}
}
function OnGUI(){
if (GUILayout.Button("++")){if (NumY < Max){NumY ++;}}
if (GUILayout.Button("--")){if (NumY > Min){NumY --;}}
}
function Update(){
if (!AudioSor.isPlaying){
var List = new Array (AudioClip);/*create a temporary Array only when needed*/
for (var A:int=0;A<sound.length;A++){
if (NumX == sound[A].track){List.Add(sound[A].Music);/*for we avoid conflicts between tracks, just add the music proved necessary*/}
}
AudioSor.clip = List[Random.Range(0,List.length)];/*randomly select a track*/
List = null;/*clean the list to not take up space in RAM*/
AudioSor.Play();
}
}
function FixedUpdate(){
if (NumX != NumY){AudioSor.volume -= 0.01;
if (AudioSor.volume <=0 || !AudioSor.isPlaying){
var List = new Array (AudioClip);/*create a temporary Array only when needed*/
for (var A:int=0;A<sound.length;A++){
if (NumX == sound[A].track){List.Add(sound[A].Music);/*for we avoid conflicts between tracks, just add the music proved necessary*/}
}
AudioSor.clip = List[Random.Range(0,List.length)];/*randomly select a track*/
List = null;/*clean the list to not take up space in RAM*/
NumX = NumY;
AudioSor.Play();
}}
if (NumX == NumY && AudioSor.volume <1){AudioSor.volume += 0.01;}
}
class Music{
var Music :AudioClip;
var track :int; /* 0=Music thriller , 1=Music for joy , 2=Horror music , 3=Music for relaxation */
}
How I can solve this problem? What is missing?
Why the error happens? InvalidCastException: Can not cast from source type to destination type.