- Home /
Why am I getting "X" is not a member of "Y" on Unity iPhone, when it works regular Unity?
Hi, I've imported a few scripts into Unity iPhone which use GetComponent, like this line here:
cursorShip.GetComponent(Cursor).ChangeColors ();
It works fine in Unity 2.6, but in Unity iPhone it gives me this error:
'ChangeColors' is not a member of UnityEngine.Component.
What the heck's going on here? Thanks!
Edited title and tags to be more generic, because this problem is not limited to GetComponent, but appears when moving any dynamic typed scripts to Unity iPhone
Answer by duck · Jan 25, 2010 at 09:24 PM
That's because Javascript in Unity iPhone forces you to use strictly typed variables, rather than having Unity dynamically change variable types for you behind the scenes.
"Cursor" is a Component. In general, components do not have a "ChangeColors()" function, and the "GetComponent" function returns a value whose type is "Component".
When you're working in regular Unity's Javascript, and you try to access your Cursor component's "ChangeColors" function, Unity helps you by automatically changing the variable's type from "Component" to "Cursor". It does this behind the scenes, and this is called "dynamic type casting". It can do this, because "Cursor" inherits from "Component".
This is one of the niceties that you have to forsake in cold harsh world of iPhone development! With Javascript in Unity iPhone, you have to specifically tell Unity what type of variable you're talking about. To use GetComponent to do what you want, you need to do this:
var cursor : Cursor = cursorShip.GetComponent(Cursor);
cursor.ChangeColors();
And in general, when developing for the iPhone in Javascript, it's a good idea to add this line to the top of each script:
#pragma strict
This forces unity to alert you to any cases where you're not using strictly typed variables, so that you can systematically iron out all these kind of bugs :)
you're welcome! (you can click the tick to mark the answer as 'accepted')
Actually, it's only necessary to do "var cursor : Cursor = cursorShip.GetComponent(Cursor);" for the first line.
If you want to do the whole thing in one line, you can use "(cursorShip.GetComponent(Cursor) as Cursor).ChangeColors();"
Your answer
Follow this Question
Related Questions
Scripting errors only when building for iPhone 2 Answers
I got a major question 1 Answer
Why is this player script not working 1 Answer
Different behavior on ipad and iphone 0 Answers
Unity to Xcode Problem 1 Answer