- Home /
Changing gameobject assigned to a variable from string
hello, I can not change a variable gameobject in my script.
npcname is a string that matches the name of gameobject..
I use this code:
GameObject.Find(triggername).GetComponent("AnimationOnTrigger").animateobject=NpcName;
but it returns the error:
InvalidCastException: Cannot cast from source type to destination type.
Try this:
var ObjectHere:Transform; //Locate your object here
ObjectHere.Find(triggername);
FlowerPotsHaveDirtInThem = ObjectHere.getComponent("AnimationOnTrigger");
FlowerPotsHaveDirtInThem.animateobject=NpcName; //Not sure how to do this part
Tell me the whole bit of the section of gameobject.find and the triggername.
Answer by Berenger · May 11, 2012 at 03:41 PM
This GetComponent only returns a Component, which doesn't have an animateobject variable. You should cast it like that (C#)
GameObject trigger = GameObject.Find(triggername);
AnimationOnTrigger animOnTrigger = trigge.GetComponent("AnimationOnTrigger") as AnimationOnTrigger;
// Or, with generics
//AnimationOnTrigger animOnTrigger = trigger.GetComponent< AnimationOnTrigger >();
animOnTrigger .animateobject=NpcName;