Hello! Sorry ... I have a "Enemy" that has a reference to another Gameobject to access its script: Code (CSharp): public GameObject fartPoint; private FartScript fartScript; 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!
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): void Start() { var player = FindObjectOfType<Player>(); fartScript = player.GetComponentInChildren<FartScript>(); }
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>
Since only one instance exists in the scene you can use this: Code (CSharp): void Start() { fartScript = FindObjectOfType<FartScript>(); }