I’m struggling with the prefab concept here and not sure what I am doing wrong.
I have a prefab that is essentially an “empty” game object. To that I have added a camera.
I have a script attached to the Empty object i.e. the prefab root from which I want to access the Camera. My problem is that I cannot seem to find it. I tried GetComponent. That returns as null i.e. it is not finding the camera.
What I am trying to understand is whether a component added in the editor by drag and drop is the same as one added in code using gameComponent.AddComponent() so that I can work out if I must use the scripted version to get access to the camera.
A hint of where I am going wrong would be good.
What you are looking for is GetComponentInChildren, and no it’s not a component its a gameObject itself.
methode 1:
GameObject pref; // the prefab (root)
Camera prefCam = pref.GetComponentInChildren<Camera>();
methode 2: (if you know the index of the camera’s gameObject)
Camera prefCam = pref.transform.GetChild(0).GetComponent<Camera>(); // 0 is the first index.
there are more methods, but these should do the job.
Perfect. Many thanks that really helps. After I posted last night I found my way through to the second method. As I currently only have the one item in the prefab it worked, it just did not feel right as I cannot be sure of the ordinal remaining the same if I change the prefab.
The first method is perfect and also clears in my head the construction of the prefab. The component belongs to a game object and the game object is a child of my prefab game object.
Thanks for your help.