Scripting errors only when building for iPhone

I have encountered a problem when building for iPhone. It is strange because it only complains for when building for iphone, but then complains at the corrected code when I try it in the editor.

i get an error on these kind of lines.

var obj : GameObject = Instantiate( coinPrefab ).gameObject;

this returns: BCE0019: 'gameObject' is not a member of 'UnityEngine.Object'.

To get this code to build, I simply removed the ".gameObject", and then it compiles fine ( but only when building for iPhone, not for testing in editor )

So my question is: Is there something wrong with this code? Or is there a discrepancy in Unity?

thats what gives me an error when building for iPhone, if i only use Instantiate(coinPrefab), then i get an error in the editor

2 Answers

2

Instantiate returns an Object, which does not have a gameObject property.

You would need to do something like this:

`var obj : GameObject = Instantiate( coinPrefab ) as GameObject;`

Hope that helps.

==

I'll try this out, but code from the scripting reference suggest that it should work even though it is an Object http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html in the second box :)

Well, yeah in some cases this would work due to the implicit typecasting allowed in Unity's JS. For example, it would work if you were instantiating a Component or some type of Monobehaviour, because they have a .gameObject property, but since you are using Instantiate to instantiate a GameObject (your Prefab), if you check the docs the GameObject class has no .gameObject because it is a GameObject. Make sense?

Instantiate returns type Object which does not have a .gameObject

var obj : GameObject = (GameObject) (Instantiate( coinPrefab ));

or

var obj : GameObject = Instantiate( foo ) as GameObject;

or

var obj : GameObject = Instantiate( foo );

...are all correct ways

In my case noone of the above worked to solve the issue (both for the editor and for iphone). I did solve it however by using a Transform var as an intermediate: var tobj : Transform = Instantiate( coinPrefab );//.gameObject; var obj : GameObject = tobj.gameObject;

it's impossible for us to know what type coinPrefab is. It could be a rigidbody for all we know. Only you and your code knows. The above answer is how to correctly cast in javascript! I am glad you have fixed your script!