I had this issue when reloading a scene or switching from one to another. The other solutions didn't work for me. In Unity 6, this is what worked:
public class ReverseMask : Image
{
private Material _customMaterial;
public override Material materialForRendering
{
get
{
if (_customMaterial == null)
{
_customMaterial = new Material(base.materialForRendering);
_customMaterial.SetFloat("_StencilComp", (float)CompareFunction.NotEqual);
}
return _customMaterial;
}
}
}