SpriteRenderer component noob question

Hi there, this is my first forum post,

I’ve recently taken up learning C# and so far I’ve been following guides and tutorials, constantly brainstorming new ideas and ways to make use of what I learn as I go.

It’s been a lot of fun. But my biggest pet peeve is that I prefer to have detailed information about what I’m learning, and sometimes tutorials simply fall short, either because things get outdated, or perhaps the author doesn’t deem it necessary to provide detailed explanation. Either way, without further ado, if anyone can explain this to me, it’d be much appreciated:

What is the difference between these two lines?

  1. SpriteRenderer spriteRenderer = gameObject.GetComponent();
  2. SpriteRenderer spriteRenderer = GetComponent() as SpriteRenderer;

They both do the same thing although I think the cast to a sprite renderer (as SpriteRenderer) in the second one is not required.

1 Like

So essentially the cast to a sprite renderer is from an outdated version? Thank you for the clarification mate! :slight_smile:

I believe so, I could be wrong though. It is hard finding tutorials which are up to date as unity seems to progress quickly often with subtle changes such as that.

that second one looks like something I’ve seen before but it used a slightly different signature, like maybe:
(typeof(className)) as Type_
And I think the cast was required (in that ‘older’ version), because it would return ‘Component’, otherwise.

That’s some stuff I remember from searching some time ago.

Besides that, they are the same. The generic version with the < > brackets like that is newer, much more common( other than older tutorials), and in my opinion, much easier :wink: