- Home /
What are the best practices to convert variable type?
I was trying to use #pragma strict and got this error:
Cannot convert '(UnityEngine.Component)' to 'GroundCheck'
It's referring to this snippet:
function start (groundCheck : GroundCheck) : GroundCheck {
if (groundCheck == null)
groundCheck = GetComponentsInChildren(GroundCheck);
if (groundCheck == null)
groundCheck = transform.Find("GroundCheckCollider").GetComponent(GroundCheck);
return groundCheck;
}
And that is the only custom function inside GroundCheck.js
Needless to say, without pragma I get no error. And the second if also doesn't bring any error.
So, how can I fix this?
I actually came up with a solution, but I'm not sure if it's adequate:
function Parse (v) : GroundCheck {return v;}
function start (groundCheck : GroundCheck) : GroundCheck { if (groundCheck == null) groundCheck = Parse(GetComponentsInChildren(GroundCheck)); if (groundCheck == null) groundCheck = transform.Find("GroundCheckCollider").GetComponent(GroundCheck); return groundCheck; }
Answer by burnumd · Feb 26, 2010 at 09:34 PM
The reason it's complaining is that GetComponentsInChildren returns an array of whatever you're looking for (that's what the parentheses around "UnityEngine.Component" in the error you posted means) and it can't convert an array of type GroundCheck to a single instance of GroundCheck. You probably want to be calling GetComponentInChildren(GroundCheck) instead, or
var groundCheckArray : GroundCheck[] = GetComponentsInChildren(GroundCheck);
if (groundCheckArray.Length > 0) {
groundCheck = groundCheckArray[0];
}
But only if you want to be really verbose. I'd recommend just using GetComponentInChildren if you don't have a reason not to.
I would never guess that parenthesis would have such a meaning. Thanks!