C# > Camera tagged MainCamera > GetComponent<[ScriptClassHere]>() returns null ?
Hi everyone
Apologies if that question has been asked already, but going through the forums (including stackexchange) does not provide me any clue about the problem I have.
Context:
In the app, I have a button on my UI allowing a camera rotation around a target. The invoked method is referring to Camera.main.gameObject which is not null (I checked through debug). I am running this app within the Unity Editor (using debug or not).
I checked the Camera and that main Camera (the only one here) is tagged as "MainCamera" as it should be. It is not null either. FollowTarget is a class inheriting MonoBehaviour (C# script). It is set on the Camera.
Problem:
Somehow, the GetComponent<[FollowTarget]> is returning null: please see failing C# code example below with comments. Please note that the other version of GetComponent is returning a result as expected:
public void RotateCameraLeft() {
FollowTarget target1 = Camera.main.gameObject.GetComponent<FollowTarget>();
/* target1 is null */
Component target2 = Camera.main.gameObject.GetComponent("FollowTarget");
/* target2 is the component I want but I cannot access its properties because it is a Component class and cannot cast it either (exception InvalidCastException (Component --> FollowTarget) */
// Method body ...
}
Can someone explain me this oddity given these methods are supposed to be the same in C# (I searched that as well)?
Any help greatly appreciated. Also, I'd be happy to hear what difference there is between these two methods as obviously, there seems to be one.
Best Regards & Season's greetings...
F.