unity3d中c#如何修改物体局部的颜色

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity3d中c#如何修改物体局部的颜色相关的知识,希望对你有一定的参考价值。

shader也都是改变整个的颜色,如果只是想改变一个局部范围内的颜色该如何做

参考技术A 修改天空盒颜色的例子(C#):
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour
public Color colorStart = Color.blue;
public Color colorEnd = Color.green;
public float duration = 1.0F;
void Update()
float lerp = Mathf.PingPong(Time.time, duration) / duration;
RenderSettings.skybox.SetColor("_Tint", Color.Lerp(colorStart, colorEnd, lerp));



修改天空盒材质的例子(C#):
// 加载所有 skybox 纹理
Texture2D sbFront = Resources.Load("Texture/Skybox/skybox_Front") as Texture2D;
Texture2D sbBack = Resources.Load("Texture/Skybox/skybox_Back") as Texture2D;
...

// 创建新的 SkyBox 材质
Material mySkyBoxMat = new Material(Resources.Load("Shaders/myOwnSkyboxShader") as Shader);

// 将所有纹理添加到材质中
mySkyBoxMat.SetTexture("_FrontTex", sbFront);
mySkyBoxMat.SetTexture("_BackTex", sbBack);

// 设置RenderSettings skybox 变量
RenderSettings.skybox = mySkyBoxMat;

稍微完整些的例子(C#):
using UnityEngine;
using System.Collections;

public class SkyboxSetter : MonoBehaviour

// 创建Skybox材质
public static Material CreateSkyboxMaterial(SkyboxManifest manifest)

Material result = new Material(Shader.Find("RenderFX/Skybox"));
result.SetTexture("_FrontTex", manifest.textures[0]);
result.SetTexture("_BackTex", manifest.textures[1]);
result.SetTexture("_LeftTex", manifest.textures[2]);
result.SetTexture("_RightTex", manifest.textures[3]);
result.SetTexture("_UpTex", manifest.textures[4]);
result.SetTexture("_DownTex", manifest.textures[5]);
return result;


public Texture2D[] textures;

void OnEnable()

SkyboxManifest manifest = new SkyboxManifest(textures[0], textures[1], textures[2], textures[3], textures[4], textures[5]);
Material material = CreateSkyboxMaterial(manifest);
SetSkybox(material);
enabled = false;


// 材质加到天空盒
void SetSkybox(Material material)

GameObject camera = Camera.main.gameObject;
Skybox skybox = camera.GetComponent<Skybox>();
if (skybox == null)
skybox = camera.AddComponent<Skybox>();
skybox.material = material;



public struct SkyboxManifest

public Texture2D[] textures;

public SkyboxManifest(Texture2D front, Texture2D back, Texture2D left, Texture2D right, Texture2D up, Texture2D down)

textures = new Texture2D[6]

front,
back,
left,
right,
up,
down
;



代码测试结果:
按照RenderSettings.skybox = mySkyBoxMat;方式设置并没有成功,用下面例子中的SetSkybox运行成功。

需要注意的是,Texture目录需要放在Resources目录下,最终的目录结构是这样的:
项目主目录/Assets/Resources/Textures/Skybox/skybox_Front.jpg
参考技术B 我现在也需要这样的效果,局部变色,请问你解决了吗? 参考技术C 答非所问的人能不能再少一点

以上是关于unity3d中c#如何修改物体局部的颜色的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D中改变模型的颜色问题

unity3D用C#脚本如何实现给物体添加力,望详细

Unity3D点击按钮让物体变透明

unity3d的四元数 Quaternion

opengl导入一个3维物体,如何修改其局部坐标系?

unity3d 材质概述 ---- shader