Beginner's syntax question on GetComponent and SpriteRenderer

Hi,

This is a stupid question, but I can’t find the answer as it seems like an accepted convention, except I am not sure what the convention is.

  1. this.GetComponent**<SpriteRenderer>**().color = Color.yellow;
    What is this <> ? I am used to seeing codes that could look like, GetComponent(SpriteRenderer) or GetComponent(“SpriteRenderer”) or GetComponent.SpriteRenderer …but I have never seen <>
    Is this a C# thing, or a unity thing? what is it called ? When is it used other than this particular instance?

While trying to research the answer on GetComponent, i came across this example :
2. HingeJoint hinge = gameObject.GetComponent(typeof(HingeJoint)) as HingeJoint;

What is this code doing? It looks to me like the 2nd as HingeJoint is unnecessary because the variable hinge was declared as HingeJoint in the first place at the beginning of the code.
Why can’t it just be:
hinge = gameObject.GetComponent(typeof(HingeJoint)) as HingeJoint;
OR
HingeJoint hinge = gameObject.GetComponent(typeof(HingeJoint))

Thank you for the help.

You are referring to two different ways of calling a GetComponent method. They both do exactly the same thing.

A C# thing, they are called generics: Generic classes and methods - C# | Microsoft Learn

Now, here’s the explanation behind both of these methods.

in the background is implement something like

public T GetComponent<T>()
{
    // Code
}

So, as you can see, there’s no need to use the “as” keyword after the GetComponent() since it returns the type passed in it through the generic field.

in the background is most likely implemented like this:

public object GetComponent(Type type)
{
    // Code
}

So, it actually doesn’t return the same type passed in, it actually returns an object which you have to cast into your desired class.

Hopefully, it makes a bit of sense, there’s a ton of this information out there already; You should have some basic info to figure out some stuff now.

2 Likes

Hi Dextozz ,

Yes, it make sense. Thank you for the explanation! It was driving me crazy earlier.
Thanks again :slight_smile:

You should almost always use this form by the way:

Renderer myRenderer = GetComponent<Renderer>();

It’s the least error prone and the least typing too.

2 Likes

Thanks @PraetorBlue , just saw this now.