Search Unity

GetComponent Generic version question

Discussion in 'Community Learning & Teaching' started by teknophyl, Sep 13, 2014.

  1. teknophyl

    teknophyl

    Joined:
    Jun 22, 2014
    Posts:
    51
    In a book I am reading I was asked to enter the following code line:

    Code (CSharp):
    1. _playerRigidBody2d = (Rigidbody2D)GetComponent(typeof(Rigidbody2D));
    From previous experience I know that there's a Generic version of GetComponent, so I refactored it:

    Code (CSharp):
    1. _playerRigidBody2d = GetComponent<Rigidbody2D>();
    Is one preferred over the other? Why?
     
  2. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    no. Use the way that makes sense.
     
  3. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    That would be the second one...
     
    SunnySunshine likes this.
  4. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    976
    Generic one should be faster because fewer calls.
     
  5. teknophyl

    teknophyl

    Joined:
    Jun 22, 2014
    Posts:
    51
    Kind of what I thought too; the conversion and type retrieval seem unnecessary. Thanks everyone.