How to detect whenever unity Camera component is created/instantiated as newly in the runtime

Hi Guys,

I was wondering if there is way to detect unity component (i.e. Camera) that is created or destroyed in the run-time dynamically.
In general I thought that Observer ,Listener and Event trigger may be a good solution if it is possible, but i have no idea how to make it work properly.

It seems that i can only do with custom game objects or components that is made by myself or is under our control.

Normally app developer are attaching Camera components inside of GameObject using by code or prefab.
Roughly, I can check current active or inactive cameras in the FixedUpdate() or Update() at every certain time (polling mechanism).
but it looks very unprofessional and may hurts render performance with unnecessary operations at every frame.

void Update() // Or FixedUpdate()
{
        ...
        Camera[] cameras = Resources.FindObjectsOfTypeAll(typeof(Camera)) as Camera[];
        foreach (Camera cam in cameras) {
            if (IsCameraRegistered(cam.gameObject.name)) {
                continue;
            }
            RegisterCurrentCameraList(cam, CurrentCameraList.Count);
        }
        ....
}

I hope someone who are experts on Unity can help me to figure out.

Why do it this way?

Why not just register a camera after you instantiate it?

Thing is that Camera is instantiated by application itself using prefab or programmatic way not plugin module, so plugin doesn’t know when application camera is created also no idea how to register it automatically without using plugin interface to register camera where it is used in application.

Test code is experiment trying and it works as expected, but it is not elegant solution.
i hope to figure out how to register dynamically created/destroyed camera in the run-time if i can use listener or event handler.

Um, Resources.FindObjectsOfTypeAll is possibly the slowest thing you could use. On every frame no less. In fact, it says so in the documentation: Please note that this function is very slow and is not recommended to be used every frame.

Let’s take a step back.

What exactly are you doing? Are you creating a plugin for others to drop into their project? If so, they will hate you for using Resources.FindObjectsOfTypeAll every frame. :smile:

1 Like

I agree, i also hate to use Resources.FindObjectsOfTypeAll() at every frame, so i am looking the way how to use something events or observer to catch.
Until now, i doubt that there is solution to solve it.