Search Unity

Is there a way for scripts on prefabs to reference in-scene objects?

Discussion in 'Scripting' started by DroidifyDevs, Mar 4, 2018.

  1. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Hello,

    In my project, I have a lot of objects that get spawned and need references to things that don't get spawned (Camera, UI etc...). To find those objects, I have to use silly-looking code:
    Code (CSharp):
    1. GameObject yesNoButtons = GameObject.FindWithTag("Canvas").transform.Find("InSettlementUI").Find("YesNoButtons").gameObject;
    Also, if I rename an object or break a parent/child relationship, it can break a lot of other code.

    Is there a better way to do this?

    Thank you!
     
  2. roykoma

    roykoma

    Joined:
    Dec 9, 2016
    Posts:
    176
    Maybe referencing all the things you need in one script that is in the scene as a singleton (Kinda like a "ReferenceManager" would work for you?

    You could do it with something like this:

    Code (CSharp):
    1.  
    2. public class ReferenceManager : MonoBehaviour {
    3.    
    4.  public static ReferenceManager Instance {
    5.         get {
    6.             if (instance == null) {
    7.                 instance = FindObjectOfType<ReferenceManager>();
    8.             }
    9.             return instance;
    10.         }
    11.     }
    12.     private static ReferenceManager instance;
    13.     public GameObject importantReference;
    14.  
    15.  
    16.     public void Awake() {
    17.         if (Instance != null && Instance != this) {
    18.             Destroy(this);
    19.         }
    20.     }
    21. }
    Where you could store all your references in the inspector of you scene.

    In your prefab scripts you can then simply do something like this:

    Code (CSharp):
    1.  
    2.     public GameObject importantReference;
    3.     public void Awake() {
    4.         importantReference = ReferenceManager.Instance.importantReference;
    5.     }
    (Or just use those references directly instead of referencing them again.)

    Don't forget to check for null of course.

    Greetings
    Roy
     
    Last edited: Mar 4, 2018
  3. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343