Set texture of projector

I want to change the frame of projector but I get this error :

"NullReferenceException: Object reference not set to an instance of an object "
at this line

projector.material.SetTexture(“_ShadowTex”, frames[frameIndex]);

This is the code I’ve used

public float fps = 30.0f;
public Texture2D[] frames;

private int frameIndex;
private Projector projector;

void Start()
{
    projector = GetComponent<Projector>();

	NextFrame();
    InvokeRepeating("NextFrame", 1 / fps, 1 / fps);
}

void NextFrame()
{
    projector.material.SetTexture("_ShadowTex", frames[frameIndex]);
    frameIndex = (frameIndex + 1) % frames.Length;
}

This answer can go a couple different ways, given lack of knowledge of the problem. If your frames collection only has one texture in it, the call to NextFrame as InvokeRepeating starts will aways target an incorrect (non-existent) array index as x modulo 0 is always x. So, the call will attempt to fetch the 2nd element of a 0 index array having length 1, which fails.

Alternatively, it’s possible that trying to access the material field of the projector without first initializing it is what causes the NullRef. You’ll want to make Materials in the editor for each possible shadow texture then modify the script to use a collection of Materials rather than Texture2Ds. Then you’ll add the materials you made to the Materials collection of this script. Again, the failure state will occur if the materials collection only has one element.

I’d change the line using the modulus to a conditional to avoid the 1-element failure state:

frameIndex++;

if (frameIndex > frames.Length)
    frameIndex = 0;