- Home /
how to typecast from GameObject
Does UnityScript typecasts objects? how?
function ItemHandler(item : GameObject) {
if(item instanceof EquippableItem) {
DoSomethingWithEquippableItem(itemtypecasted);
}
}
Answer by Aeless · Feb 20, 2012 at 01:45 PM
for that kind of behavior you're actually adding components to game objects. you don't derive from game object. if you want to check whether a game object has a specific component, use something like:
if (GetComponent<EquippableItem>() != null)
{
}
but just a reminder, in unity, you don't actually need to know the type of the object/component or anything actually. just send a message whenever you want something to happen. then handle that event in the class itself. in your case:
class EquippableItem : MonoBehaviour
{
void OnMyEvent()
{
DoSomethingHere();
}
}
then whenever you want to trigger that just call
targetGameObject.SendMessage("OnMyEvent")
for the game object we're talking about.
take a look at these methods from component:
http://unity3d.com/support/documentation/ScriptReference/Component.SendMessage.html http://unity3d.com/support/documentation/ScriptReference/Component.BroadcastMessage.html http://unity3d.com/support/documentation/ScriptReference/Component.SendMessageUpwards.html
also for accessing components:
http://unity3d.com/support/documentation/ScriptReference/Component.GetComponent.html http://unity3d.com/support/documentation/ScriptReference/Component.GetComponentInChildren.html
well, instanceof works. so I guessed that if instanceof works, why wouldn't a typecast?
well, it seems that instanceof doesn't work, mono has tricked me, sorry.