- Home /
Why am I getting this error ?
I have a line of code in my script to access and enable/disable a certain component on a game object...
var freezePlayer = GameObject.FindGameObjectWithTag("Player").GetComponent("CharacterMotor");
Works fine.
When I change it to this...
var freezePlayer = GameObject.FindGameObjectWithTag("Player").GetComponent("MainCamera");
I get this error message...
NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Any suggestions please guys ???
Is $$anonymous$$ainCamera a script? Try doing .GetComponent($$anonymous$$ainCamera);
No, sorry possibly didn't explain that too well. Its the actual $$anonymous$$ainCamera that is attached to the first person controller
Answer by tanoshimi · Jan 11, 2015 at 08:01 AM
Try
var freezePlayer = GameObject.FindGameObjectWithTag("Player").GetComponent(Camera);
Already tried that. Got this error message -
$$anonymous$$issingComponentException: There is no 'Camera' attached to the "First Person Controller" game object, but a script is trying to access it. You probably need to add a Camera to the game object "First Person Controller". Or your script needs to check if the component is attached before using it. (wrapper dynamic-method) UnityEngine.Camera.Camera$set_enabled$System.Boolean (object,object[]) Boo.Lang.Runtime.RuntimeServices.SetProperty (object,string,object) SwitchCameras.Update () (at Assets/Scripts/SwitchCameras.js:21)
:(
Well, that error is pretty self-explanatory... it means there is no 'Camera' attached to the "First Person Controller" game object, but a script is trying to access it. You probably need to add a Camera to the game object "First Person Controller".
The unity first person controller has a camera 'built in' by default.
(second component in list, $$anonymous$$ain Camera with Tag - $$anonymous$$ainCamera)
That's not a component on the same object tagged with "Player" though - that's a component on a child object. Use
var freezePlayer = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren(Camera);
Answer by ElDo · Jan 11, 2015 at 08:46 AM
Since the Camera is not a Component i don't think you can get your reference to the Camera with GetComponent. You could either use a Tag and get the Camera with GameObject.FindGameObjectWithTag("MainCamera") or you could get it by Name for example:
GameObject.FindGameObjectWithTag("Player").transform.FindChild("MainCamera")
or even with:
Camera.main
you would have to check the js Versions of the above code since i do only use c# i' not sure if the Syntax is the same.