最终效果
思路
根据uv中的x取数组中的对应下标和uv中的y比较取色。
shader中只支持固定数组,请保持脚本和shader中的数组长度一致
shader源码
Shader "QQ/Histogram"
{
Properties
{
_BarColor("Bar Color",Color) = (0.0,0.8,0.0,1.0)
_BackColor("Back Color",Color) = (0.4,0.4,0.0,0.2)
_BarSpace("Bar Space",Range(0,1)) = 0.8
}
SubShader
{
Tags {
"RenderType" = "Transparent"
"Queue" = "Transparent"
}
LOD 100
Pass
{
Zwrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#define Length 20 //定义你需要多少个数据
uniform fixed4 _BarColor;
uniform fixed4 _BackColor;
uniform float _BarSpace;
uniform float _Values[Length];
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag(v2f i) : SV_Target
{
float center = 1.0 / Length;
int index = i.uv.x / center;
fixed4 col = _BackColor;
if (abs(i.uv.x % center / center - 0.5) / 0.5 < _BarSpace)
if (i.uv.y < _Values[index])
{
//柱颜色的控制
col = _BarColor;
col.rgb *= _Values[index]*2;
}
return col;
}
ENDCG
}
}
}
脚本控制代码
public class HistogramControl : MonoBehaviour
{
//数组长度要符合shader中定义的
public float[] values;
Material mat;
void Start()
{
mat = GetComponent<MeshRenderer>().material;
}
void Update()
{
SetData(values);
}
public void SetData(float[] values)
{
mat.SetFloatArray("_Values", values);
}
}