Automatic conversion of materials into UV offsets?

Let’s say for the sake of argument I have 100 mesh objects, each with about 8 materials applied to it, (though not always the same 8. Imagine a bunch of cars, where the tires all have the same material, windows have the same material, but the body could be painted a different colour, so there’s a material for red car, for blue car, for grey car, for white car, etc.)

But I’m trying to put this in a computer game, where it will be more efficient to render if each object uses only one material. I’ve done this manually before, (based off this tutorial to start) but the idea that there’s 100 objects, I’m wondering how I could automate it.

Basically I guess I’d want to be able to specify, all faces with material A will have their UVs within square A in the texture, all faces with material B will have UVs within square B, etc. Any ideas?

I’m considering I might be able to piece together a Python script if I can figure out all the individual commands.