- Home /
What's the best way to grab script references after instantiation
When I instantiate a say a monster in runtime, I need to access for example its NavMeshAgent and have to call GetComponent. Even if I have a script on the bugger to store all his components so I only have to make one GetComponent I still have to call at least once per, yes? Is there a better/faster way?
Answer by winterfluxstudio · May 19, 2018 at 07:27 PM
1) Find the object via a tag at runtime and then get it's components? (example getting a script component)
private GameObject Monster1;
private Monster1Script monster1Script;
void Start()
{
Monster1 = GameObject.FindWithTag("Monster1")
// get the Monster1Script.cs component of the Monster1 GameObject
monster1Script = Monster1.GetComponent<Monster1Script>();
}
2) If you are not using tags (or multiple monsters share the same tag) you would have to use public static GameObject Find(string name);
I already have a reference to the object post instantiation simply using
GameObject go = Instantiate(myGameObject);
but that doesn't award me it's components, I still have to grab anything on the GameObject itself using GetComponent. I don't think there is a better way, but maybe there is.
Your answer
![](https://koobas.hobune.stream/wayback/20220612163002im_/https://answers.unity.com/themes/thub/images/avi.jpg)