Making new material instance of sharedMaterial in editor mode

I would like the ability to make a new instance of a material in a scene or in a prefab and let it be saved with the scene or prefab. This will enable easy customization of materials without the need for manually duplicating a material in the Project view and using that instead.

The code below works for materials in a scene, but if the material is part of a prefab and that prefab is used in another scene the Material reference will be null. I am assuming the material was stored in the original scene and not in the prefab, which makes the error.

Anyone got any ideas on how to solve this?

[CustomEditor(typeof(MeshRenderer))]
public class MeshRendererInspector : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        Renderer renderer = target as Renderer;
        if (GUILayout.Button("Test Instancing"))
        {
            renderer.sharedMaterial = new Material(renderer.sharedMaterial);
        }
    }
}

renderer.materials = new Material[1];
renderer.materials[0] = new Material(renderer.sharedMaterial);