0
votes

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.

1
Do you have the reference to that CHILDObject? First: Don't do this inside the Update function. Second: Switch to C#.Muhammad Farhan Aqeel
It looks like you're accessing the first value in the array, which I assume would be your original material. You're not changing anything here.Eliasar
I think @Eliasar is right. Try using ... = arrayMAterial[1];. Also, are you using an old version of Unity just so you can use UnityScript?Ruzihm

1 Answers

1
votes

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.