Passing variables from Script to a Shader

Hey guys,

Im having trouble passing variables from C# script to a shader. I had success with a separate vertex/fragment shader, however, I can't seem to pass variables to a surface shader. Is this the problem or is there something wrong with my code? I'm trying to pass in a position variable, as well as a delta time variable. Thanks, code below

Shader "SonarShader" {
Properties
{
  _PlayerPosition("Player Position", Vector) = (1,1,1,1)
  _TimePassed("Time", float) = 0
}

SubShader { 
    Tags { "RenderType" = "Transparent" } 
    Cull Off

  CGPROGRAM
  #pragma surface surf Lambert
  #include "UnityCG.cginc"

  struct Input
  {
      float2 uv_MainTex;
      float3 worldPos;
  };

  sampler2D _MainTex;
  float4 _PlayerPosition;
  float _TimePassed;

  void surf (Input IN, inout SurfaceOutput o)
  {
      IN.worldPos.x += _PlayerPosition.x;
      IN.worldPos.y += _PlayerPosition.y;
      IN.worldPos.z += _PlayerPosition.z;
      float radius = length(IN.worldPos);
      float scale = 0.5f;
      float time = _TimePassed;
      float speed = 1000 * time * scale;
      float min = (-30 + speed);
      float max = (0 + speed);

      if(radius > min && radius < max)
        clip( sin( (radius) - speed) );
      else
        clip(-1);
  }
  ENDCG

} 

Fallback "Diffuse"

}

2 Answers

2

Nice question...

Check out google:

http://www.google.com/search?client=opera&rls=en&q=Passing+variables+from+Script+to+a+Shader+unity3d&sourceid=opera&ie=utf-8&oe=utf-8&channel=suggest

And this seems to be more what you're asking...

http://forum.unity3d.com/threads/62770-passing-custom-variables-into-surface-shader

Lol believe me, I have hit pretty much every link in that google search and have already been to that thread :) For whatever reason the variables I'm passing into this shader just aren't being read by the program. I used the same code for a vertex/fragment shader and it worked, so I'm reaching my wits end with this.

I'm not sure you're allowed to modify the vertex' world position like that. You're more likely to manage to do what you want by making a temporary float3 storing whatever value is in IN.worldPos, and then add your vector to that.

I guess you can because I got it working about five minutes ago. I was making a mistake on the script side. I was trying to send parameters to a global material in the class. I switched it to iterate through my GameObjects and send in the variables for each of their individual shaders and it worked.