Search Unity

Using same procedural code in shader and script

Discussion in 'General Discussion' started by HonoraryBob, Mar 28, 2021.

  1. HonoraryBob

    HonoraryBob

    Joined:
    May 26, 2011
    Posts:
    1,214
    Does anyone know of a relatively painless way to coordinate shader-based procedural code (for a map in this case) with script-based code (to check points on the map)? Obviously I could translate the shader code into C# but that means maintaining two pieces of code to the produce the same map. I've been toying with the idea of having the shader write to a rendertexture which can then be accessed by a script, which might work but it seems a bit sticky. Anyone have a better idea?
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    Generate procedural maps or whatever is needed in C#. You can use DOTS to assist with performance. Then pass results to shader. No need for duplication of code.
     
  3. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,571
    it would be easier to do this in C++.

    Hlsl is relatively close to C/C++ and in unity it supports includes. Which means you would be able to use shared include files between script and native code and reduce number of duplications this way.

    In C#... I don't believe there's a sane way to do it, although someone definitely tried to write a source translator.
     
  4. HonoraryBob

    HonoraryBob

    Joined:
    May 26, 2011
    Posts:
    1,214
    C++ is only available in Unity Pro though, right?
     
  5. Murgilod

    Murgilod

    Joined:
    Nov 12, 2013
    Posts:
    10,157
    Unity Pro doesn't have exclusive features like that anymore unless you're working with a version pre-5.x
     
  6. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,571
    You can use C++ as a native plugin in all tiers. Been this way since the very first release of unity 5.
    However, you can't really drive monobehaviors from C++ directly.
     
  7. HonoraryBob

    HonoraryBob

    Joined:
    May 26, 2011
    Posts:
    1,214
    I'm using 5.0.1, so I guess I can use C++ ?
     
  8. Murgilod

    Murgilod

    Joined:
    Nov 12, 2013
    Posts:
    10,157
    Yes, but I can't really recommend using 5.0.1 even within the 5.x cycle at this point. Even 5.4.6 is a better option than that at this point unless you're mired in tech debt locking you to that early a version.
     
  9. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,571
    Yes, you can. Or, at least you SHOULD be able to, because i don't recall state of C++ native plugin support in 5.0.1.

    You'll still need to write some glue to interface with C++ dll, though.
     
  10. MDADigital

    MDADigital

    Joined:
    Apr 18, 2020
    Posts:
    2,198
    Like a webassembly for shaders :D