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

GetComponent(MyScript) on hundreds of object good or bad to do?

Discussion in 'Scripting' started by ZealousAppex, Oct 23, 2017.

  1. ZealousAppex

    ZealousAppex

    Joined:
    May 3, 2015
    Posts:
    17
    I have one main script and I want to access some function from objects that are dynamical created.
    Is this bad on performance or cause any issue in the future to do:
    Code (CSharp):
    1.     private MainCode MainCode;
    2.     private void Start()
    3.     {
    4.         MainCode = GameObject.FindGameObjectWithTag("MainCode").GetComponent<MainCode>();
    5.     }
    6.  
    7.     void OnCollisionEnter(Collision other)
    8.     {
    9.         if (other.gameObject.tag == "SomeObject")
    10.         {
    11.  
    12.             if (MainCode.isDead) //check main code
    13.             {
    14.                 MainCode.DoSomeThing(); //Call function from maincode
    15.             }
    16.         }
    17.     }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If it's singular and used that much, I'd probably use a singleton myself.
    Another option: use a static method on MainCode.

    It's also possible, if you have some kind of spawner or object creator, that you could keep the reference to "MainCode" there, and pass the reference to any newly created game object/script that way.

    I like those sorts of ideas for good practice.
     
    Last edited: Oct 24, 2017
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Is it possible you are looking for a Unity Singleton pattern? Here's an implementation, but you can always just roll your own.

    http://wiki.unity3d.com/index.php/Singleton

    I'm not even going to get into the whyfores and wherehows of if a singleton is good or not.
     
  4. ZealousAppex

    ZealousAppex

    Joined:
    May 3, 2015
    Posts:
    17
    thank you so much, I will go with a Singleton!