- Home /
Is it possible to use getComponent<>() without assigning a GameObject? Is there another way to do it?
Hi all,
Going through my game scripts and checking stuff works and there isnt anything unnessesary. Changing variables in another script and actions etc i use gameObjectVar.GetComponent<gameObjectVarScript>().getScript();
I havent used this next one really, other than for getting objects ive instantiated in an array.
spawner = GameObject.FindGameObjectWithTag("spawner");
Is there any other way of doing this? Or do i have to assign the gameObjectVar every time? Its hard to explain. I feel that creating a variable which i attach the gameobject to in the inspector for each script is messy.
It may not actually be messy and its the most effective way to do it.
Answer by Syoori · Jan 20, 2016 at 04:01 AM
@No1Survivalist Hoping I understood your question.
The only reason to store the reference to a particular game object or a reference to that object's component is if you're going to perform multiple actions on that Component or GameObject. If it's just a oneshot value/variable change, you probably don't need to store the object, you can simply tack on the GetComponent to the end of your FindGameObjectWithTag().
That being said, you definitely want to minimize the amount you're calling GetComponent<>() or FindGameObjectWithTag(""), as these can bog down your code if used in an Update function or Coroutine.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Disabling a script in c# not working for some reason 1 Answer
GetComponent with Standard Assets? C# 1 Answer
Add and destroy instantiated gameobject in linkedlist C# 1 Answer