Changing gameobject assigned to a variable from string

I can not change a variable gameobject in my script.

npcname is a string that matches the name of gameobject…

I use this code:


but it returns the error:

InvalidCastException: Cannot cast from source type to destination type.

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;