Adding an image effect at run time with script usingUnity 5

This question refers to Unity 5

I’m trying to add the fisheye.cs image effect that’s contained in the new Standard assets to my camera at runtime.

I have a CreateCamera.cs script in which I’ve included

using UnityStandardAssets.ImageEffects;

The Fisheye.cs class that’s included in the Standard assets is not public, so I’ve altered it to be public like so

Before

    class Fisheye : PostEffectsBase

After

    public class Fisheye : PostEffectsBase

In my CreateCamera.cs script I can then create a new Gameobject with a camera and apply the Fisheye effect

	GameObject cameraObject= new GameObject();
	Camera cameraComponent= cameraObject.AddComponent<Camera>();
	Fisheye fisheye= cameraObject.AddComponent<Fisheye>();

When I run the game I can see that the fisheye component has been added to my camera gameobject, but the shader and material are missing like below, there is also the following debug message.

Missing shader in UnityCam1 (UnityStandardAssets.ImageEffects.Fisheye)

However, when I just drag the fisheye script onto the camera from the project I don’t have this problem.

42521-fisheyepaint.png

The problem is that the Fisheye.cs script is loosing it’s connection to the Shader.

As a workaround I can assign the FishEye shader to my script with a public Shader variable, and then manually apply the Shader as show below.

I don’t really like this as an answer as

  1. The FishEye.cs script has to be modified
  2. The Shader needs to be assigned separately

If anyone has got a better solution that would be great!

	public Shader fishEyeShaderPublic;
...

	Fisheye fisheye= cameraObject.AddComponent<Fisheye>();
	fisheye.fishEyeShader = fishEyeShaderPublic;