如何在Unity3D中分配给一个游戏对象的两种材质之间切换?

时间:2019-05-24 15:48:47

标签: unity3d unityscript game-development

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

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

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

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

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

1 个答案:

答案 0 :(得分:1)

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

    }
}

请确保将材质和渲染器分配给组件,否则会出现错误!

Component in Unity Editor

hth。