Generate object color based on position

Is there way to generate color for whole object basing on his position in world space?

What I need to do, is to paint hex planes randomly from preset colors.
The obstacle is I can’t use material property blocks, becasue it will break batching. For this reason I came up with idea to generate color (in shader) from field position, but I can’t make it correctly.
So far I tried something like this:


but it generates unwanted results:

Could someone tell me what I did wrong? Or even better question - Is this good way to make it at all?
Maybe this approach is wrong and there is better and easier solution?

Hi @Qriva ,

To answer what you did wrong - I’m not sure what you are trying to accomplish by subtracing those positions. You would need to get a static/non-changing value for one object (a hex). Then use that value to sample a gradient or a texture2D to get one solid color for a single tile. To get this done, you could define a value like 0,0,0 and then change it from object space to absolute world space. This way you should get values that are different for each object but same for every vertex of that object.

But it’s still a bit problematic/limited as the colors will change as soon as you move the object even slightly. If this is ok for your use case, if you got something like completely static environment, it might be worth using as it’s not really complex to set up. But I might myself consider other alternatives as it’s not really flexible solution and I’m not 100% sure if it would work without any artifacfs all the time.

1 Like

Not sure how this would work with shader graph etc but my approach to this (pre urp and hdrp) would be material property block with gpu instanced shader. The material property block would expose a single vector which is the colour to draw and then i would update these inside a monobehaviour on every frame as needed. Good luck!

Thank you very much!
I did subtraction, because I tried to get world position from the object space, but I understood wrong how it actually works. Anyways this is exactly what I wanted.

I think it should do the work, but do you mean any particular other solution? I would try something else, but I can’t see any easy and not costful solution.

I just meant that it’s not really that flexible, that’s all. If it works for your specific use case, great.

1 Like

Hi there. Could you do me a favour and elaborate on HOW you actually solved this? Thanks!

That was some time ago :roll_eyes:

Well, the approach above (as Olmi already said) is not flexible. If you know the math you can do anything you want, but in reality you have no control over fields. Right now I would just use vertex color to do that. In addition if you use URP batcher it becomes way easier to design game with good performence.
It’s a bit more “advanced”, but if you need hex fields, this tutorial might be helpful: https://catlikecoding.com/unity/tutorials/hex-map/