Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to reference a class that is outside my unity script using GetComponent.

private FlyThroughCamera camera;

void Start () 
    camera = GetComponent(typeof(FlyThroughCamera)) as FlyThroughCamera;

Although the class exists the cast is failing and returning null.

The other class is defined as:

public class FlyThroughCamera : MonoBehaviour

Where have I gone wrong?


Linked FlyThroughCamera

share|improve this question
Are you sure you have added the FlyThroughCamera component to your gameobject? – nathan Jan 12 '14 at 16:04
Also no need to tag this with unityscript since it seems you are using C# : ) – nathan Jan 12 '14 at 16:12
I have added the FlyThroughCamera on my GameObject in the inspector but the cast will revert it to null. If I delete the cast code then I will get a warning about hiding inherited members because it is not instantiated in any way. – user1423893 Jan 12 '14 at 16:25
If you just log the return of your GetComponent call without the cast, what does it print? – nathan Jan 12 '14 at 16:43
You do not have any FlyThroughCamera component. I think you are misunderstanding the basics of Unity3D. – nathan Jan 12 '14 at 16:56
up vote 0 down vote accepted

I would caution against shadowing the field.

I recommend the generic form of GetComponent().

private FlyThroughCamera flyCamera;

void Start () 
     flyCamera = GetComponent<FlyThroughCamera>();
     flyCamera .DoSomething();
share|improve this answer
GetComponent still returns null, even though the class exists and is linked via the Inspector window. – user1423893 Jan 12 '14 at 16:27
That's strange?... It might help if you add a screenshot of the inspector to your question. – Kelly Thomas Jan 12 '14 at 16:30
I have added a screenshot as requested. – user1423893 Jan 12 '14 at 16:41
There is no FlyThroughCamera component on that game object! getComponent() will return null if unable to find a component of the specified type. – Kelly Thomas Jan 12 '14 at 16:53
You have however already defined a value for your camera variable, so just remove the GetComponent() line and it should work. – Kelly Thomas Jan 12 '14 at 16:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.