AddComponent Doesn't work with Post Effects??

I am trying to add a post effect like Bloom to the camera using AddComponent. I immediately get a message saying a shader is missing. For a post effect like DepthOfField34, I get an error because of a missing shader. But when you click and drag one of these scripts onto the camera, they work great, but I can’t find anywhere that these shaders are set, including the associated Editor scripts. Where are these default shaders set and why doesn’t AddComponent do so properly??

That’s probably because they set up some default references on the script. Default references are only used inside the editor when you add a component via inspector. You should either:

  • Create a prefab of an object that has the script attached and all necessary links setup and simply instantiate the prefab when you need it.
  • Search for the right shader manually in the script and assign it manually.

If you click on the DepthOfField34 script, you should see in the inspector its default public arguments. They are however ignored if you add DepthOfField34 from a script.

A solution may be to add the default public arguments of DepthOfField34 to your own script, like this:

	public Shader dofBlurShader;
	public Shader doFShader;
	public Shader bokehShader;
	public Texture2D bokehTexture;
	
	// Use this for initialization
	void Start () {
		DepthOfField34 d = gameObject.AddComponent<DepthOfField34>();
		d.dofBlurShader = dofBlurShader;
		d.dofShader = dofShader;
		d.bokehShader = bokehShader;
		d.bokehTexture = bokehTexture;
	}

Note that I don’t know why the public arguments in the DepthOfField34 are not visible, since I didn’t see the HideInInspector flag…