首页 > 解决方案 > 如何在 Unity3D 中分配给一个游戏对象的两种材质之间切换?

问题描述

我在一个游戏对象上附加了两种材质,我想做的是在几秒钟后从一种材质切换到另一种材质。

在 Unity3D 中,在我选择的 Gameobject 的检查器菜单下,在材质子标题下方的 MeshRenderer 标题上,我将大小从 1 增加到 2。我为两个新创建的元素分配了两种材质。但是当我运行场景时,材质不会切换。

public var arrayMAterial : Material[];
public var CHILDObject : Transform;

function Update() {
    CHILDObject.GetComponent.<Renderer>().material = arrayMAterial[0];
}

没有错误消息。它只是没有切换到新材料。

标签: unity3dunityscriptgame-development

解决方案


这是一个快速的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];

    }
}

请务必将材质和渲染器分配给组件,否则会出错!

Unity 编辑器中的组件

hth。


推荐阅读