Prefabs calling functions

Helloz…

I have a question about Optimisation / Performance for mobile device…
I have alot of prefabs being instantiated into the game, (for mobile, its not ideal… i know)
In the game, i have an Empty game object that has a script that holds many FUNCTIONS…

Being a prefab, i cannot CACHE anything that is IN the game…into a variable via the editor

Id like the prefabs to locate that empty gameObject… and call on the function

Ive tried:

  1. GameObject.Find that
    object…GetComponent(Script)… and
    then Script.Function().
  2. GameObject.Find… and Send Message
  3. GameObjectFindByTag (apparently
    faster)
  4. Find it via a static
    variable: Script.StaticVariable.Function()
  5. Hierarchy it to a parent…
    Transform.parent.GetComponent(Script).Function

Hope im making sense >.<

Would like to ask what is the fastest method for an Instanced Prefab to call upon a function being held by an Empty Game Object.
And if it theres other methods than the ones i have listed, then i dont know them :frowning: And would like your wisdom!!

Thanks!!

1 Answer

1

Your 4th option: Find it via a static variable: Script.StaticVariable.Function() is what we call a singleton design.

Example

public class Processor: MonoBehaviour
{
    private static Processorinstance;
 
    void Awake() 
    {
       if (instance != null && instance != this) 
       {
         Destroy( this.gameObject );
         return;
       } 
       else 
       {
         instance = this;
       }
    }
 
    public static Processor GetInstance() 
    {
       return instance;
    }

    public Vector3 NormalFunction( Vector3 a ) {
       ...
    }
}

By using static variables and functions, you can refer to the Processor from any script without any Find() or variable-assignment.

You can just use it as:

Processor.GetInstance().NormalFunction( ... );

I am quite sure that this (static variable) is the fastest among the 5 options. (If anyone’s opinion differs from mine, feel free to enlighten me)

Gah... its like the method that i used the least >.< But if a method has a name to it..(singleton design), must be pretty good then. Ill start replacing everything with that then. Thanks heaps Chronos! Now you have me looking up more "named" methods :P

Just to be careful, you should do some research, look at some references before you make the modifications. I used singleton-design in AudioManagement (SFX and stuff), GameManagement(Play-pause-loadlevel), and sometimes GUI(A centralized GUI script)