Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

SpriteRenderer component noob question

Discussion in 'Scripting' started by Tyrannastrasz, May 8, 2017.

  1. Tyrannastrasz

    Tyrannastrasz

    Joined:
    May 8, 2017
    Posts:
    8
    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<SpriteRenderer>();
    2. SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>() as SpriteRenderer;
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    They both do the same thing although I think the cast to a sprite renderer (as SpriteRenderer) in the second one is not required.
     
    Tyrannastrasz likes this.
  3. Tyrannastrasz

    Tyrannastrasz

    Joined:
    May 8, 2017
    Posts:
    8
    So essentially the cast to a sprite renderer is from an outdated version? Thank you for the clarification mate! :)
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    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.
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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 ;)