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. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Instance or GetComponent?

Discussion in 'Scripting' started by yigitdurmuss, Sep 26, 2022.

  1. yigitdurmuss


    Jun 2, 2022
    Hello, i want to ask i have a script named "x" and almost every time i need to access to the script. Because i instantiate prefabs in game so these prefabs needs to get "x" and i am using.

    Code (CSharp):
    1. private x xScript;
    2. private GameObject xScriptAttachedObject;
    4. private void Awake()
    5. {
    6.     xScriptAttachedObject = GameObject.Find("xScriptAttachedObject");
    7. }
    9. private void OnEnable()
    10. {
    11.     xScript = xScriptAttachedObject.GetComponent<x>;
    12. }
    So i look for a better way and find make an instance. So i added this to my "x" script;

    Code (CSharp):
    1. public static x Instance;
    3. private void Awake()
    4. {
    5.      Instance = this;
    6. }
    And my question is; Is second way better than first one? And using the second way cause a problem in future?
    Last edited: Sep 26, 2022
  2. MelvMay


    Unity Technologies

    May 24, 2013
    So you know, here's how to post code on the forums:
  3. yigitdurmuss


    Jun 2, 2022
    MelvMay likes this.
  4. kdgalla


    Mar 15, 2013
    The general consensus is that you should avoid trying to find a game object by name if you can help it.

    It looks like what you are trying to do is a Singleton. If you google you can find examples of how to code this in a monobehavior. It's essentially the same thing you did in your second example, except people also like add code to ensure that there is never more than one instance at a time.

    If you were to accidentally create two game objects with that same script, Instance will be set to which ever instance initialized last.
  5. yigitdurmuss


    Jun 2, 2022
    Actually i am obsessed with optimization side. Approx. 50 prefabs will instantiating same time. As i know using GetComponent and GameObject.Find slower than instance.

    Long story short, i need to get the some data from "x" script for prefabs. Which way is better to do this?
  6. Kurt-Dekker


    Mar 16, 2013
    I've worked in codebases like that. It's a DISASTER.

    DO NOT OPTIMIZE "JUST BECAUSE..." If you don't have a problem, DO NOT OPTIMIZE!

    If you DO have a problem, there is only ONE way to find out. Always start by using the profiler:

    Window -> Analysis -> Profiler

    Failure to use the profiler first means you're just guessing, making a mess of your code for no good reason.

    Not only that but performance on platform A will likely be completely different than platform B. Test on the platform(s) that you care about, and test to the extent that it is worth your effort, and no more.

    Remember that optimized code is ALWAYS harder to work with and more brittle, making subsequent feature development difficult or impossible, or incurring massive technical debt on future development.

    Notes on optimizing UnityEngine.UI setups:

    At a minimum you want to clearly understand what performance issues you are having:

    - running too slowly?
    - loading too slowly?
    - using too much runtime memory?
    - final bundle too large?
    - too much network traffic?
    - something else?

    If you are unable to engage the profiler, then your next solution is gross guessing changes, such as "reimport all textures as 32x32 tiny textures" or "replace some complex 3D objects with cubes/capsules" to try and figure out what is bogging you down.

    Each experiment you do may give you intel about what is causing the performance issue that you identified. More importantly let you eliminate candidates for optimization. For instance if you swap out your biggest textures with 32x32 stamps and you STILL have a problem, you may be able to eliminate textures as an issue and move onto something else.

    This sort of speculative optimization assumes you're properly using source control so it takes one click to revert to the way your project was before if there is no improvement, while carefully making notes about what you have tried and more importantly what results it has had.
    Ryiah likes this.
  7. spiney199


    Feb 11, 2021
    The either look up the means to do a singleton, or just have the object instantiating these prefabs have a reference to the object they need and pass it through after instantiating.
  8. Ryiah


    Oct 11, 2012
    I recommend breaking this habit as soon as possible as it just leads to reduced productivity for what is almost always an unnoticeable performance improvement. Very rarely will it lead to anything that matters and without proper profiling it can even lead to a reduction in performance.

    That said if you're convinced everything must be optimized you should be trying to do as much as possible in DOTS not MonoBehaviours. DOTS is a framework that is designed to be highly optimized out of the gate whereas a lot of their code based around MonoBehaviours is made for ease of development not maximum efficiency.

    Just as an example I remember a video a number of years ago by one of the engineers responsible for assisting companies with optimizing their projects that mentioned Unity UI was dependent on Camera.main which was just FindObjectsByTag under the hood. If you're not aware the Find methods are known for very poor performance.
    Last edited: Sep 27, 2022
    Kurt-Dekker likes this.
  9. Kurt-Dekker


    Mar 16, 2013