- Home /
Attaching and Removing a script to the main camera
Hi there,
I have a copy of the pro licence, I want to be able to control the scripts that I attach to the main camera: blur, sepia etc etc. How do I do this? How do I script that when the character collides with an object an effect gets turned on on the camera?
Many thanks! Matthew
ANSWER FOR JS for destroy script instance
if (Input.GetButton ("Fire1") && GetComponent (FooScript))
Destroy (GetComponent (FooScript));
Answer by whydoidoit · May 22, 2012 at 10:41 AM
To add one:
gameObject.AddComponent("TypeNameOfTheScriptYouWantToAdd")
or
gameObject.AddComponent(typeof(TypeOfTheScriptYouWantToAdd))
To remove:
Component.Destroy(instanceOfScriptToDestroy)
On the main camera that will look like Camera.main.gameObject.AddComponent etc
Say you have a script MyBehaviour:
Camera.main.gameObject.AddComponent(typeof(MyBehaviour))
To remove you could do this:
foreach(var c in Camera.main.gameObject.GetComponents<MyBehaviour>())
Component.Destroy(c);
This latter is a catch all in case you added more than one of the component. If there is only one for sure:
Component.Destroy(Camera.main.gameObject.GetComponent<MyBehaviour>());
Another approach would be, to add all relevant scripts to the Camera beforehand, so that you can also parametrize them to your likings. Then disable all effects, and individually set/reset the "enabled" flag of those effects you want to activate/deactivate during your gameplay (for example, using Camera.main.GetComponent(typeof(BlurEffect)).enabled=true; etc.)
Thanks guys for the reply! Wolfram's response sounds a little easier so I'll try to work with that for now. I created a script with the code:
function OnTriggerEnter(trigger: Collider){ Camera.main.GetComponent(typeof(GreyscaleEffect)).enabled=true; }
The script on the main camera is called "GrayscaleEffect" and it is unchecked. I am getting this error:
Assets/Scripts/CameraEffects_1.js(2,41): BCE0005: $$anonymous$$ identifier: 'GreyscaleEffect'.
Any ideas? Is JS the right script to use??
You are spelling GreyscaleEffect different ways - could that be your problem?
Oh woaw now I feel really silly haha thanks Whydoidoit!! Fixed it!!!