Unity中URP下实现水体(C#动态生成渐变图)

文章目录


前言

在之前的文章中,我们已经完成了URP下水体的所有效果。

但是,水的颜色用一个变量来控制让水深浅颜色渐变变化,太过于单调。

所以,我们可以使用纹理采样的方式来替换水的颜色。

这个纹理可以由C#来动态生成渐变图,以达到随机的效果。


一、Shader部分

因为,该纹理是用C#代码传入。所以,属性面板可以不用定义该纹理。

在hlsl中,申明纹理和采样器即可

1、申明水渐变图纹理和采样器

TEXTURE2D(_WaterColorTex);

SAMPLER(sampler_WaterColorTex);

2、在片元着色器,进行纹理采样,并且输出

float4 waterTex = SAMPLE_TEXTURE2D(_WaterColorTex,sampler_WaterColorTex,i.uv.xy);

return waterTex;


二、C#脚本部分

1、我们新建一个C#脚本

2、我们定义两个变量

  • 渐变色传入(这是Unity的API)

public Gradient waterGradient;

  • 定义需要动态生成的纹理

public Texture2D rampTexture;

3、在Start内,new 一个Texture2D(宽,高)

rampTexture = new Texture2D(512, 256);

4、定义一个Color[宽*高]的颜色数组

Color[] colors = new Color[rampTexture.width * rampTexture.height];

5、使用循环,依次给颜色数组,填入传入的渐变色

for (int i = 0;i < colors.Length;i++)

{

colors[i] = waterGradient.Evaluate((float)i/colors.Length);

}

6、 使用颜色数组,生成纹理

rampTexture.SetPixels(colors);

rampTexture.Apply();

7、把该纹理传入Shader对应的材质球纹理中

this.GetComponent().material.SetTexture("_WaterColorTex",rampTexture);


三、最终代码

C#脚本

复制代码
using System;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Arts.Shader.URP.P4.P4_8
{
    public class WaterColor : MonoBehaviour
    {
        [Header("水体颜色渐变")]
        public Gradient waterGradient;
        public Texture2D rampTexture;

        //Start is called before the first frame update
        void Start()
        {
            rampTexture = new Texture2D(512, 256);
            Color[] colors = new Color[rampTexture.width * rampTexture.height];
            for (int i = 0;i < colors.Length;i++)
            {
                colors[i] = waterGradient.Evaluate((float)i/colors.Length);
            }

            rampTexture.SetPixels(colors);
            rampTexture.Apply();
            this.GetComponent<MeshRenderer>().material.SetTexture("_WaterColorTex",rampTexture);
        }
    }
}
相关推荐
虚行5 小时前
C#上位机工程师技能清单文档
开发语言·c#
小白杨树树8 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#
Tiger_shl9 小时前
三大并发集合ConcurrentDictionary、ConcurrentBag、ConcurrentQueue
开发语言·c#
时光追逐者10 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图
我是唐青枫11 小时前
C#.NET FluentValidation 全面解析:优雅实现对象验证
c#·.net
YuanlongWang11 小时前
C# 设计模式——工厂模式
开发语言·设计模式·c#
时光追逐者11 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 58 期(2025年10.13-10.19)
微软·开源·c#·.net·.netcore
开发游戏的老王12 小时前
虚幻引擎虚拟制片入门教程目录
游戏引擎·虚幻
躺平的赶海人13 小时前
C# Dictionary 线程安全指南:多线程下操作 Dictionary<string, DateTime> 的加锁策略
java·安全·c#
张人玉15 小时前
C#WPF如何实现登录页面跳转
ui·c#·wpf