- Home /
Works in Unity, but can't be build
Hey guys, I kinda have a very confusing problem here.
I use following script for experiment purposes:
var objectPrefab : Transform;
function Update() { var count = Input.touchCount;
for (i=0;i<count;i++)
{
var touch : Touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began) {
var testObject = Instantiate (objectPrefab, transform.position, Quaternion.identity);
testObject.rigidbody.AddForce (transform.forward *2000);
}
}
}
The script is attached to the camera, co u can shoot objects from the camera if you touch the screen. And in the Unityplayer, with unity remote it works like a charm. But when I try to build it I get:
Assets/Scripts/Joystick 1.js(13,31): BCE0019: 'rigidbody' is not a member of 'UnityEngine.Object'.
and
Error building Player because scripts had compiler errors UnityEditor.HostView:OnGUI()
Why does it work in the player, but doesnt build itself? When I click on the error he shows me the "testObject.rigidbody.AddForce (transform.forward *2000);" Line.
Answer by Bunny83 · Feb 27, 2011 at 03:38 PM
I'm not an iPhone developer (i'm a win. user) but i read somewhere that you have to use strict typing on iPhone but i'm not sure about that. Anyways, this error looks like that's what you have to do. Instantiate returns always a reference of type UnityEngine.Object. The real type is of course Transform but that's figured out at runtime due to dynamic typing. Try this:
var testObject : Transform = Instantiate (objectPrefab, transform.position, Quaternion.identity) as Transform;
testObject.rigidbody.AddForce (transform.forward *2000);
EDIT
In UnityScript (as far as i know) the "as-cast" is the only way to do an explicit cast. In C# you also have the C-style casting:
Transform testObject = (Transform)Instantiate (objectPrefab, transform.position, Quaternion.identity);
For more information on scripting in general and casting see this reference:
http://answers.unity3d.com/questions/5507/what-are-the-syntax-differences-in-c-and-javascript
yeah, your code works perfect. But why is it like this? what does "as Transform" change?
It explicitly casts the returned reference (which is of type Object) into the type Transform. Take a look at this wikipedia article about typecasting: http://en.wikipedia.org/wiki/Type_conversion I'm not sure if the second type of casting works on iPhone. I'll add the second method as well.