unity3d - 如何在 Unity3D 中分配给一个游戏对象的两种材质之间切换?
问题描述
我在一个游戏对象上附加了两种材质,我想做的是在几秒钟后从一种材质切换到另一种材质。
在 Unity3D 中,在我选择的 Gameobject 的检查器菜单下,在材质子标题下方的 MeshRenderer 标题上,我将大小从 1 增加到 2。我为两个新创建的元素分配了两种材质。但是当我运行场景时,材质不会切换。
public var arrayMAterial : Material[];
public var CHILDObject : Transform;
function Update() {
CHILDObject.GetComponent.<Renderer>().material = arrayMAterial[0];
}
没有错误消息。它只是没有切换到新材料。
解决方案
这是一个快速的C# 脚本,它将在延迟后循环遍历一组材料。
using UnityEngine;
public class SwitchMaterialAfterDelay : MonoBehaviour
{
[Tooltip("Delay in Seconds")]
public float Delay = 3f;
[Tooltip("Array of Materials to cycle through")]
public Material[] Materials;
[Tooltip("Mesh Renderer to target")]
public Renderer TargetRenderer;
// use to cycle through our Materials
private int _currentIndex = 0;
// keeps track of time between material changes
private float _elapsedTime= 0;
// Start is called before the first frame update
void Start()
{
// optional: update the renderer with the first material in the array
TargetRenderer.material = Materials[_currentIndex];
}
// Update is called once per frame
void Update()
{
_elapsedTime += Time.deltaTime;
// Proceed only if the elapsed time is superior to the delay
if (_elapsedTime <= Delay) return;
// Reset elapsed time
_elapsedTime = 0;
// Increment the array position index
_currentIndex++;
// If the index is superior to the number of materials, reset to 0
if (_currentIndex >= Materials.Length) _currentIndex = 0;
TargetRenderer.material = Materials[_currentIndex];
}
}
请务必将材质和渲染器分配给组件,否则会出错!
hth。
推荐阅读
- python - “utf-8”编解码器无法解码字节 0xe2:无效的继续字节错误
- javascript - 使用 javascript 在条件上添加 var
- spring-boot - 如果身份验证/授权失败,如何自定义 Spring Security 响应?
- scala - 如何使用 RDD、数据框、数据集计算数组中重复的值
- laravel - Laravel - 日期范围搜索过滤器不起作用
- vue.js - 如何更改 Vuestic Admin 主题图标
- windows - 使用 Chef 之类的工具进行开发 PC 设置
- java - 使用 Jersey 到 API 的 POST 请求出错,与 POSTMAN 一起工作正常
- windows - 无法使用 USB 上的批处理文件在桌面上创建空白 .txt 文件
- ios - UserDefaults 数组返回为空