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.

@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.