playMaker

Author Topic: Does GetComponent<X>() impact performance?  (Read 4956 times)

Tricky_Widget

  • Junior Playmaker
  • **
  • Posts: 62
Does GetComponent<X>() impact performance?
« on: March 11, 2015, 06:46:59 PM »
With the upgrade to Unity 5, I'm running into many considerations with the API change.  The most common is the deprecation of component references such as go.renderer.  The new method would be go.GetComponent<Renderer>().

The automatic API upgrader seems to do a pretty good job of replacing these sorts of calls.  However, it seems to blindly replace all instances of renderer with GetComponent<Renderer>().  Which means it's getting called over and over again.  I'm developing for mobile, so performance is a critical consideration.

I'm wondering if there is a notable difference between situations such as:
Code: [Select]
material = go.GetComponent<Renderer>().material;
isVisible = go.GetComponent<Renderer>().isVisible;
enabled = go.GetComponent<Renderer>().enabled;

and this:
Code: [Select]
renderer = go.GetComponent<Renderer>();
material = renderer.material;
isVisible = renderer.isVisible;
enabled = renderer.enabled;

It seems like the latter would be more efficient, but I'm not familiar with the subtleties of Unity scripting.

Does anyone know?  Thanks!

Lane

  • Administrator
  • Hero Member
  • *****
  • Posts: 2511
  • Mender of the past
    • Cleverous
Re: Does GetComponent<X>() impact performance?
« Reply #1 on: March 11, 2015, 09:39:29 PM »
It was basically doing this in the background before anyway from what I understand. The idea is to just cache it by putting it in awake/start for the better performance.
Products by Cleverous
|| Vault Core : Database
|| Vault Inventory : Multiplayer Inventory
|| Vault Attributes : Character Stats
|| That Hurt! : Dmg Floaties
|| Quinn : 3D

Alex Chouls

  • Administrator
  • Hero Member
  • *****
  • Posts: 4002
  • Official Playmaker Support
    • LinkedIn
Re: Does GetComponent<X>() impact performance?
« Reply #2 on: March 11, 2015, 10:05:17 PM »
In many cases an occasional call to GetComponent is fine, but you want to avoid calling it in loops or every update (e.g., actions that can be called every frame).

In Unity 5, Playmaker actions that used to use those properties now use caching to avoid calling GetComponent too often. For example, if you look at Add Force, it derives from ComponentAction which implements the basic caching of components.

If you want you can also derive actions from ComponentAction to take advantage of caching...