Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Performance: Storing objects or Transform.GetChild()?

Discussion in 'Scripting' started by whoft, Jun 3, 2023.

  1. whoft

    whoft

    Joined:
    Jul 1, 2021
    Posts:
    25
    I have a scene with a player prefab.
    When the player dies, 4 objects are retrieved from the player's hierarchy with Transform.GetChild, and then acted on once. The player will probably die once every 30s - 1m.
    Code (CSharp):
    1.                 thisController.isDead = true; //this.gameObject.GetComponent<FPSController>().
    2.                 thisWeapon.isDead = true; //this.gameObject.GetComponent<PlayerWeapon>()
    3.                 thisGrabber.canPickupObjects = false; //grabSlot.GetComponent<PlayerGrabItem>()
    4.                 thisPostProcess.enabled = true; //this.transform.GetChild(0).gameObject.GetComponent<PostProcess>()
    Would it be more performant to store script references of the objects (like in the code, the variables accessed are references to scripts on the objects) or look up the objects every time (like in the comments)?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,612
    Well what does your intuition tell you? I would think not having to look for something every frame should obviously be more performant.

    Referencing objects via the inspector is the bread and butter of Unity, so ideally you should always do so when possible (there are times when you can't).

    And if you do need to find something, you should just cache the reference so you only look for it once.

    Mind you shouldn't speculate on performance. The profiler is there to measure these things for you. And in most case... it doesn't matter for the average project.
     
    Bunny83 and Ryiah like this.
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,965
    Four requests every 30 to 60 seconds is completely meaningless to any processor made in the past few decades.

    Though in this case you're likely going to see rounding errors that are larger than the actual time to complete this task with how little is being done.
     
    Last edited: Jun 3, 2023
    Bunny83 likes this.
  4. whoft

    whoft

    Joined:
    Jul 1, 2021
    Posts:
    25
    Thank you!