- Home /
How to get camera out of player prefab after game started and player spawned?
I have this buildSystem Script that requires a camera, so that the player is able to see the building previews. The script is on a Build System empty game object but the player with the camera ist not in the scene until the game is started. How could I, after the game started and the player is spawned, get the camera from the player and put it in the inspector of the BuildSystem script in the empty game object?
Answer by GetLitGames · May 15, 2020 at 11:24 AM
It depends on your build system script, sometimes they do depend on a Camera being in that field of the inspector in Awake() and Start() but hopefully not.
Create a script/new class (Like SetBuildScriptCamera.cs), and add a public GameObject MyCamera; void Start() { FindObjectOfType().CameraProperty = MyCamera; } at the top, then save file and go back into Unity and attach SetBuildScriptCamera onto the Player. Drag the Normal Camera onto your MyCamera property in the inspector.
BuildScript and CameraProperty will be whatever the names of the script and property on that script that you need to have set to your camera.
If you get errors or problems still, it's possible the Awake() or Start() of the BuildSystemScript requires the camera. If that's the case, you might be able modify their Update() so that it checks like: if (CameraProperty == null) CameraProperty = GameObject.Find("Normal Camera").GetComponent(); or something like that. If you don't want to or can't modify their script, you can add similar code to your own script.
There are many ways to get access to other objects, the best way is by reference and dragging objects into a field in the inspector since you can still use them even if the object is disabled. The find functions won't find objects or components that are inactive or disabled.
Another common method of getting references to other objects is via a Singleton pattern, but that is basically FindObjectOfType and won't work if the gameobject is inactive or the component is disabled.