- Home /
Get typeof component
I want my script to Get the main camera when it starts, I cannot just place it into the Camera variable because It wont let me since I'm instantiating the object, I've looked for a bit to try find answer to this but couldn't find one, The camera is a child of a Empty, Here is the line I have tried but failed with.
Void Start()
{
fpsCam.GetComponent(typeof(Camera));
}
Answer by I_Am_Err00r · Jul 30, 2019 at 05:32 PM
Void Start()
{
fpsCam = GameObject.FindObjectOfType<Camera>();
}
This should also work:
Void Start()
{
fpsCam = Camera.main;
}
Quick edit, I see you say you are instantiating the camera, is that getting instantiated at start (or Awake())? Because if this script runs before whatever script that instantiates the camera runs, it won't recognize the camera; you need to make sure that this script is ran after the other one, or maybe do an Invoke() at start like this:
Void Start()
{
Invoke("FindCamera", .1f);
}
public void FindCamera()
{
fpsCam = Camera.main; //or you could use the other example of GameObject.FindObjectOfType<Camera>();
}
$$anonymous$$isunderstood, Its not the camera that is being instantiated it is an enemy object that requires the camera for the Health bar so it is always readable by the user. Nonetheless the top one was what I was looking for, thanks for the help!