Search Unity

Find a GameObject for a PreFab

Discussion in 'Scripting' started by Feretro, Dec 1, 2019.

  1. Feretro

    Feretro

    Joined:
    Apr 18, 2017
    Posts:
    45
    Hello!
    Sorry ... I have a "Enemy" that has a reference to another Gameobject to access its script:

    Code (CSharp):
    1.  public GameObject fartPoint;
    2. private FartScript fartScript;
    3.  
    I have this "fartScript" in a (of course!) fartPoint GameObject.

    With my Enemy still in the Hierarchy I can "drag & drop" that GameObject in editor, but ... when I make my Enemy a PreFab ... It loses the reference, so I need to assign fartPoint that is a CHILD of another gameObject to my Enemy via script.

    How can I achieve this?

    I have something like

    Player
    I -> FartPoint (and here I have that script I want to access)

    So I need to access that (Player's) child game object before that script.

    Thanks for your help!
     
  2. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    291
    If you have only one FartScript, you can just use FindObjectOfType<FartScript>() to find the reference from Start.

    If you have more than one FartScript, then you'll need to first find the Player using some method (if you add a Player component to it you can use FindObjectOfType<Player>), and then you can use GetComponentInChildren to find the FartScript from the child GameObjects of the player.

    Code (CSharp):
    1. void Start()
    2. {
    3.     var player = FindObjectOfType<Player>();
    4.     fartScript = player.GetComponentInChildren<FartScript>();
    5. }
     
  3. Feretro

    Feretro

    Joined:
    Apr 18, 2017
    Posts:
    45
    Hi SisusCo!
    Thanks for your reply! I have only one fart script, but I would instantiate different Enemies! Anyway It gives me an error.

    There is "no reference" for <Player>
     
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    291
    Since only one instance exists in the scene you can use this:

    Code (CSharp):
    1. void Start()
    2. {
    3.     fartScript  = FindObjectOfType<FartScript>();
    4. }
     
unityunity