- Home /
How to reduce usage of GetComponent()? (instantiate, prefabs)
I'm using the following code to instantiate a prefab:
GameObject dialog = Instantiate(Prefab.ChooseNameDialog) as GameObject;
NameScriptController controller = dialog.GetComponent<NameScriptController>();
controller.Property = propertyValue;
I am concerned about using GetComponent()
like this. It looks like bad style. There is no type safety. All I can really do is try to remember to add my script to the prefabs.
In other instances, I've been able to replace GetComponent()
calls with public variables of type ScriptName
. I would like to find a similar solution for instantiating prefabs.
One GetComponent
per Instantiate
isn't going to make much of a difference. The biggest killer in performance is your Instantiate
. Use an Object pool and you will have to use neither Instantiate
not GetComponent
.
This is not a performance question. It is about code maintainability.
You could check if your prefab has the component and add it if not.
NameScriptController controller = dialog.GetComponent<NameScriptController>() ?? dialog.AddComponent<NameScriptController>();
controller.Property = propertyValue;
You can also force a GameObject to have an other script using the RequireComponent attribute https://docs.unity3d.com/Documentation/ScriptReference/RequireComponent.html
Your answer
Follow this Question
Related Questions
Get unity to recognize prefab in C# 2 Answers
Variable of prefab has not been assigned 2 Answers
Instantiate Prefabs. Errors. 2 Answers
Play iTween on instantiated prefab 1 Answer