Search Unity

Transition between materials with a public method

Discussion in 'Getting Started' started by tylerlybb, Oct 19, 2016.

  1. tylerlybb

    tylerlybb

    Joined:
    Jul 21, 2016
    Posts:
    51
    I have this script (below) that ping pongs back and forth between two materials. How would I change it so that instead of ping ponging over and over I can cause the transition to happen through using animation events? So, for example, I could have an animation that on frame 60 I trigger a transition to material 2 and on frame 120 transition back to material 3.

    I know how to create an anim event inside an animation to call a method in a script. What I don't know how to do is how to create public method in this script that can cause a transition to happen from material 1 to material 2. Can someone help? Thanks in advance!!

    A follow-up question to that is this: how do I have 3 materials to swap between?

    Code (CSharp):
    1.  using UnityEngine;
    2. using System.Collections;
    3. public class swap_mats : MonoBehaviour {
    4.      // Blends between two materials
    5.      public Material material1;
    6.      public Material material2;
    7.      public float duration = 2.0F;
    8.      public Renderer rend;
    9.      void Start() {
    10.          // At start, use the first material
    11.          rend = GetComponent<Renderer>();
    12.          rend.material = material1;
    13.      }
    14.      void Update() {
    15.          // Ping-pong between the materials over the duration
    16.          float lerp = Mathf.PingPong(Time.time, duration) / duration;
    17.          rend.material.Lerp(material1, material2, lerp);
    18.      }
    19. }