Why do we instantiate with a generic?

We havent really delved deep into the concept of generics. Does this come later or in another course?
Also, could someone explain why we use

Instantiate<DamageText>(damageTextPrefab, transform);

instead of just

Instantiate(damageTextPrefab, transform);

?

Thank you!

The first will return a DamageText component of a newly instantiated object and the other will return a new gameObject. What you use should depend on what you need.

1 Like

So

Instantiate<DamageText>(damageTextPrefab, transform);

is the same as

Instantiate(damageTextPrefab, transform).GetComponent<DamageText>();

?

Essentially, yes.

Actually, the C# compiler can derive what the generic type is.

[SerializeField] DamageText damageTextPrefab;

var explicitType = Instantiate<DamageText>(damageTextPrefab, transform);
var derivedType = Instantiate(damageTextPrefab, transform);

If damagetTextPrefab was declared as DamageText (as above), then it will return DamageText in both cases.

Damn I stand corrected. Good pick up. I had to look up the docs to check. I could have sworn that it was a GameObject type as that parameter, not a generic.

You weren’t wrong, though. If we have the variable declared as a GameObject your answer is correct, provided the game object has a DamageText component

1 Like

So if both cases return the same thing, why add the ?

If the types are the same, it doesn’t matter if it’s there or not. Adding it just makes it clear to other developers (and yourself) what you wanted to get out of it. Like I said, though, if the prefab was declared as a GameObject, you would have to specify the generic type, if GameObject is not what you want out.

1 Like

Privacy & Terms