Search Unity

Random offset of texture per object

Discussion in 'Shaders' started by runonthespot, Nov 24, 2016.

  1. runonthespot

    runonthespot

    Joined:
    Sep 29, 2010
    Posts:
    305
    Hi all,

    Does anyone have any idea how I can randomly offset the uv of a texture per object in a shader? I don't want to use the material offset as I need to keep drawcalls low.

    Essentially I have a bunch of shapes on screen with a texture that is tiled and don't want every object to look the same, so if I could somehow randomly offset the uv, that would help.

    The texture should move with the object, which kind of implies that I have to pass a random number into the shader somehow but currently my best guess is sticking this on some unused part of the geometry (uv2? maybe)? but seems overkill for essentially one x/y value.

    Any other hints?

    Thanks!
    Mike
     
  2. Michal_

    Michal_

    Joined:
    Jan 14, 2015
    Posts:
    365
    You can try to use instancing. It was designed to solve this very problem. I tried Unity's take on instancing back in the beta and I wasn't impressed but maybe it is working properly now...

    Your options are limited otherwise. You need at least one per instance value that would serve as a seed for pseudo random generator in shader. As you said, you can use vertex attributes. I would use vertex color if I could. It takes least amount of space.
    The only other per instance value available is world matrix. You can use world position as a seed for static objects. Dynamic objects are trickier but you can theoretically use scale (assuming scale never changes). You can extract scale from world matrix and use it as a seed. Most of your object probably have the same scale though. What you can do is to use slightly different scale for every object. Something like scale = Random.Range(scale - 0.01, scale + 0.01). The difference wouldn't be visible and it would be good enough as random generator seed. It is kind of a hack but it could work.
     
    Shippety likes this.
  3. runonthespot

    runonthespot

    Joined:
    Sep 29, 2010
    Posts:
    305
    In the end, since I was using custom geometry anyway, it was easy enough to create uv3 and add it there - just the same offset for the object to every vertex. Sounds overkill somewhat, but works fine and doesn't appear to have added much overhead.

    The random scaling idea was interesting, but I was concerned that it would break batching since only objects with the same scale are batched.

    I'll take a look at the instancing stuff at some point too.

    Thanks!