cursor arrows
cursor arrows

Reputation: 1

How to switch between two materials assigned to one gameobject in Unity3D?

I've got two materials attached to one gameobject and what I want to do is switch from one material to another after a few seconds have gone by.

In Unity3D under the inspector menu on the Gameobject that I have selected, on the MeshRenderer heading underneath the materials sub-heading I have increased the size from 1 to 2. I've assigned two materials to the two newly created elements. But when I run the scene the materials do not switch.

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

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

There are no error messages. It just does not switch to the new material.

Upvotes: 0

Views: 1680

Answers (1)

Jerome Maurey-Delaunay
Jerome Maurey-Delaunay

Reputation: 1070

Here's a quick C# Script that will cycle through an array of materials after a delay.

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];

    }
}

Be sure to assign the materials and renderer to the component, otherwise you will get errors!

Component in Unity Editor

hth.

Upvotes: 1

Related Questions