DoF effect from Code


I’m having a bit of trouble with the DoF effect. I’m trying to add the class as a component to my main camera at run time and set some of its settings.

private DepthOfField mDOF;
...{other code here}...

//Set up the DoF effect for the camera
mDOF = mMyCamera.gameObject.AddComponent<DepthOfField>();
mDOF.aperture = 0.5f;
mDOF.focalSize = 0.0f;
mDOF.focalLength = Vector3.Distance(mMyCamera.transform.position, mPlayer.CurrentPosition);
mDOF.blurSampleCount = DepthOfField.BlurSampleCount.Medium;
mDOF.enabled = true;

the problem is that I keep getting a null reference exception with the following;

Am I missing something obvious or is it not possible to add the DoF component at run time?


Apparently it needs shaders assigned to it.
To determine what shaders I added the following line to DepthOfField.CheckResources() and I added the DOF effect. (Don’t leave this in or you’ll get spammed when playing the scene):

Debug.LogFormat("dofHdrShader: {0}

dx11BokehShader: {1}
dofHdrMaterial: {2}
dx11bokehMaterial: {3}", dofHdrShader, dx11BokehShader, dofHdrMaterial, dx11bokehMaterial);

That told me I needed to do this to instantiate this kind of component:

UnityStandardAssets.ImageEffects.DepthOfField dof = Camera.main.gameObject.AddComponent<UnityStandardAssets.ImageEffects.DepthOfField>();
            dof.dofHdrShader = Shader.Find("Hidden/Dof/DepthOfFieldHdr");
            dof.dx11BokehShader = Shader.Find("Hidden/Dof/DX11Dof");
            dof.enabled = true;

And all seems to be just fine with it.

Caveat: If you want this to run in a build you will need to add those two shaders to the Graphic Settings “Always Included Shaders” section. The can be found in the “Standard Assets/Effects/Shaders/_DepthOfField” folder. The DepthOfFieldHdr is apparently names DepthOfFieldScatter.