enable/disable image effects in code

I currently have a game object selectable by the user and I'm trying to figure out how to enable depth of field when selected and disable when its not.

Any help would be appreciated.

1 Answer

1

First setup a way to talk to the DepthOfField component from your gameobject

public mainCamera : GameObject; // set this to the main camera in the inspector
private dof : DepthOfField;

function Start () {
    var dof : DepthOfField = mainCamera.GetComponent(DepthOfField);
}

then either tweak the settings

function Focus () {
    // set the focus settings, I'm making these numbers up
    // but this should be a decent starting point.
    dof.focalZDistance = 0;
    dof.focalZStart = 0;
    dof.focalZEnd = 1000;
}

function Blur () {
    var distanceToFocusedObject = // get the distance to the focused object
    // set the focus settings
    dof.focalZDistance = distanceToFocusedObject;
    dof.focalZStart = distanceToFocusedObject - 5;
    dof.focalZEnd = distanceToFocusedObject + 5; // I'm still making these numbers up
}

or toggle enabled

function Focus () {
    dof.enabled = false;
}

function Blur () {
    dof.enabled = true;
}

I haven't tested any of this code but I think the approach is valid.

Also I bet animating `focalZStart` and `focalZEnd` in the `Focus` and `Blur` functions would look pretty cool.

Awesome help, I managed to get it working with your code, thanks very much.

–

Where are you finding the script names for the image effects (e.g. Blur, DepthOfField) and the values such as focal.ZDistance, focalZStart? I'd like to be able to tweak these for other image effects.

–

I added the effect to my camera and got the script name from the inspector eg blur would be "BlurEffect" depth of field "DepthOfField" etc, also by opening up the script you can see the variables that are tweakable. Cheers!

–

Thanks! Easy when you know how... ;)

–