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??

2 Answers

2

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.

The first one won't work because the scripts have to be on a camera. The second would work, but I was hoping to avoid that. Might have to. The third option would be to have the post effects disabled on the camera until I need them. Not sure which route I will go.

In your case i would go your third solution ;) It's the easiest one and actually avoids loading stuff in-game. Having it already in the scene has also the advantage that you can reference the script from other scripts to enable / disable the effect.

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…

Yep, sorry. My answer had to be validated, and it took a few hours... Thanks for the precision about the editor scripts.