Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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;
    camera.DoSomething();
}

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?

EDIT:

Linked FlyThroughCamera

share|improve this question
    
Are you sure you have added the FlyThroughCamera component to your gameobject? –  nathan Jan 12 at 16:04
    
Also no need to tag this with unityscript since it seems you are using C# : ) –  nathan Jan 12 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 at 16:25
    
If you just log the return of your GetComponent call without the cast, what does it print? –  nathan Jan 12 at 16:43
    
Debug.Log(GetComponent(typeof(FlyThroughCamera))) returns null –  user1423893 Jan 12 at 16:53

1 Answer 1

up vote 0 down vote accepted

I would caution against shadowing the MonoBehaviour.camera 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 at 16:27
    
That's strange?... It might help if you add a screenshot of the inspector to your question. –  Kelly Thomas Jan 12 at 16:30
    
I have added a screenshot as requested. –  user1423893 Jan 12 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 at 16:53
1  
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 at 16:55

Your Answer

 
discard

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.