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. Dismiss Notice

Is it possible to access a GameObject on the scene from a Prefab?

Discussion in 'Scripting' started by jensmcatanho, Nov 18, 2014.

  1. jensmcatanho

    jensmcatanho

    Joined:
    Jul 11, 2014
    Posts:
    21
    I have a prefab of a bullet (that does not exist on the scene until someone instantiates it) that has a script describing it's behaviour. It's behaviour depends on the wind which is sorted randomly by another script of a GameObject (that already exists on the scene). My problem is that I can't put the GameObject that already exists on the Inspector of the bullet's prefab, so how can I access those informations without unnecessarily creating a bullet when the game starts?
     
  2. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    You can do it by having a static field named "Instance" in your wind controlling script and use that in your bullet scripts.

    Or in Codenese:
    Code (CSharp):
    1. public class WindController : MonoBehaviour
    2. {
    3.   public static WindController Instance { get; private set; }
    4.   public Vector3 wind;
    5.  
    6.   private Awake()
    7.   {
    8.     Instance = this;
    9.   }
    10.  
    11.   private void OnDisable()
    12.   {
    13.     Instance = null;
    14.   }
    15. }
    16.  
    And in your bullets:
    Code (CSharp):
    1. public class Bullet: : MonoBehaviour
    2. {
    3.   private void Update()
    4.   {
    5.     var wind = WindController.Instance.wind;
    6.     // Go to town.
    7.   }
    8. }
    Also look up the Singleton pattern. I don't particularly like it because the pattern above is simpler to write and easier to understand, but it gets used a lot and is well documented.
     
  3. jensmcatanho

    jensmcatanho

    Joined:
    Jul 11, 2014
    Posts:
    21
    Thanks, it works just as I wanted! But let me see if I understood the code, Awake() sets Instance to the current GameObject and OnDisable() sets Instance to null when the GameObject is destroyed?
     
  4. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    Yes, that's what is being done. Or, to be more specific, it's setting it to hte MonoBehaviour rather than the GameObject. The distinction is not that important but it's good to be aware of it.

    This is predicated on having one instance of the object in your scene. You can (and should) add checks to ensure that Instance is set to Null in the Awake function, and likewise add a check in OnDisable to ensure that Instance in not Null.