Search Unity

Singleton Class vs GetComponent

Discussion in 'Scripting' started by Zamatrius, Jul 4, 2015.

  1. Zamatrius

    Zamatrius

    Joined:
    Mar 25, 2015
    Posts:
    11
    What would be faster :
    Code (CSharp):
    1. object.GetComponent<Player>().hp;
    or:
    Code (CSharp):
    1. Player.SingletonPlayer._S.HP;
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    Speed? Speed isn't something I'd compare Singleton to GetComponent on. It's a matter of design rather than speed.

    Technically speaking, as long as SingeltonPlayer, and _S, were actual fields, it'd be faster because you're just accessing a field. Where as GetComponent needs to find the component on the object.

    But you could locally cache the GetComponent instance and have the same exact speed.

    Singleton has NOTHING to do with the speed of accessing something. And instead about enforcing a single instance of a class.
     
    bigboybifdick and Kiwasi like this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Which is faster, a submarine or a car? There is an answer, but the real question for picking between the vechiles is are you driving on land, or under the water?

    Choose the best tool for the problem at hand. Singletons and GetComponent both solve different jobs.
     
    lordofduct likes this.