GetComponent vs AddComponent

//----------------------------------- Code 1
public spawnerPrefab;

var temp = Instantiate(spawnerPrefab, spawnPoint.position, Quaternion.identity).GetComponent<Spawner_Enemy>();

//----------------------------------- Code 2

var temp = Instantiate(new GameObject(), spawnPoint.position, Quaternion.identity).AddComponent<Spawner_Enemy>();

Both codes do the same thing, but I want to know which one is better.

GetComponent attempts to get a reference to a component that is currently attached to the object. It returns null if it was not found.

AddComponent is used to attach a new component to the object. Calling AddComponent multiple times will attach multipe instances of the component to the object.

You said both codes are working as expected. Try executing Code 2 and then look in the Inspector while the game is running. Does the object have 2 x Spawner_Enemy scripts attached?


My apologies. The last part of my answer (about the double scripts) is wrong. I didn’t notice the new GameObject part in your example.

You have several different things in your two cases which makes it difficult to say which is better. Your first case instantiates a premade and serialized prefab. That means you can preconfigure everything in that prefab asset and the clone will have the same settings as you set them up in the inspector for the prefab.

As i said in the comment, in your second case you actually create two gameobject. new GameObject() already creates an empty gameobject which Instantiate will clone. You then attach a new “Spawner_Enemy” component to your cloned gameobject. Note that the Spawner_Enemy component will have it’s default values. Also keep in mind that a prefab can be a much more complex object with several components and child objects.

Finally your first case can be simplified even more. Instantiate will return the same object type that you pass in. So what it returns depends on the type of your prefab variable. If you declare a GameObject prefab variable, Instantiate will return the GameObject reference of the cloned object.

However you can also declare the prefab variable of type “Spawner_Enemy”. (Note if you change the type you have to reassign the prefab in the inspector). When you call Instantiate on a component reference Unity will clone the whole gameobject as well. Though in addition Instantiate will directly return the cloned “Spawner_Enemy” component. So your first case would become:

public Spawner_Enemy spawnerPrefab;
var temp = Instantiate(spawnerPrefab, spawnPoint.position, Quaternion.identity);

var temp = Instantiate(spawnerPrefab, spawnPoint.position, Quaternion.identity).GetComponent();
This is the best. Because spawnerPrefab has already component named “Spawner_Enemy” so when this code run, it don’t spend time to add the component