- Home /
Implicit Downcast warning.
Hello everyone.
Since a while I get this warning
Assets/#Scripts/Player.js(32,35): BCW0028: WARNING: Implicit downcast from 'UnityEngine.Component' to 'UnityEngine.AudioSource'.
And here is my code:
private var SND_toggle_item :AudioSource;
function Start()
{
// audio sources
var factory = gameObject.GetComponents(AudioSource);
SND_toggle_item = factory[6];
}
What do I need to change in order to get rid of this warning?
Answer by vexe · Oct 31, 2013 at 11:55 AM
You could explicitly downcast it, if you wanna get rid of that warning.
Instead of casting the thing, just use the generic explicit type-defining GetComponent
, like:
var factory : AudioSource[] = gameObject.GetComponents.<AudioSource>();
You shouldn't need to cast, after that point.
GetComponents
return a Component[]
- You're storing that in your factory
variable - now factory
is a Component[]
- In your next line, you're assigning factory[6]
which is a Component
to SND_toggle_item
which is an AudioSource
- which inherits Behaviour
, which in turn inherits Component
. In other words, an AudioSource
is a specific type of Component
. So in your assignment, you're trying to assign a Component
to an AudioSource
- Component
is higher in the inheritance tree, than AudioSource
- In C#, that assignment would give you an error, in JS it appears it's giving just a warning (Another reason I don't like JS) - It appears it's automatically (implicitly) doing the downcast, meaning it's down-casting factory[6]
to an AudioSource
to reach equivalency and type-match in your assignment. (Remember, when you assign Y to X, there has to be a type-match between them, otherwise the assignment is invalid)
I hope it's clear now.
Sorry to bother again,but that line of code gives me errors.. (expecting,unexpected token)
Thanks for explanation! I managed to fix these errors by using something more related to what I actually needed. .PlayOneShot().
But with you line I fixed my other scripts. Thanks again.
You mean before the "lesser than" character <
Answers comments ate it.
Your answer
Follow this Question
Related Questions
Sound system not working correctly 0 Answers
'Play' is not a member of 'Object' 1 Answer
Issue with OnTriggerEnter. 1 Answer
expecting (, found 'Update' and unexpected char: 0x200B. 2 Answers
Player not taking any damage 2 Answers