Demo_SignSwitcher.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. This script switches a renderer's material.
  3. Email :: thomas.ir.rasor@gmail.com
  4. */
  5. using UnityEngine;
  6. using System.Collections;
  7. public class Demo_SignSwitcher : MonoBehaviour
  8. {
  9. public Material[] materials;
  10. public bool autoswitch = false;
  11. public float delay = 6f;
  12. public float transitionTime = 1f;
  13. public KeyCode nextKey = KeyCode.RightArrow;
  14. public KeyCode prevKey = KeyCode.LeftArrow;
  15. bool isswitching = false;
  16. int currentId = 0;
  17. float cphase = 0f;
  18. Renderer r;
  19. float t = 0f;
  20. void Start()
  21. {
  22. r = GetComponent<Renderer>();
  23. t = delay;
  24. StartCoroutine( GoToMaterial() );
  25. }
  26. public IEnumerator GoToMaterial()
  27. {
  28. if ( materials.Length > 0 )
  29. {
  30. Material nextMat = materials[ currentId ];
  31. isswitching = true;
  32. while ( cphase > 0f )
  33. {
  34. cphase -= Time.deltaTime / transitionTime;
  35. r.sharedMaterial.SetFloat( "_Phase" , cphase );
  36. yield return new WaitForEndOfFrame();
  37. }
  38. r.sharedMaterial = nextMat;
  39. while ( cphase < 1f )
  40. {
  41. cphase += Time.deltaTime / transitionTime;
  42. r.sharedMaterial.SetFloat( "_Phase" , cphase );
  43. yield return new WaitForEndOfFrame();
  44. }
  45. isswitching = false;
  46. }
  47. }
  48. void ShiftMaterial( int offset )
  49. {
  50. currentId = ( int )Mathf.Repeat( currentId + offset , materials.Length );
  51. StartCoroutine( GoToMaterial() );
  52. }
  53. void Update()
  54. {
  55. if ( isswitching || r == null )
  56. return;
  57. if ( autoswitch )
  58. {
  59. if ( t > 0f )
  60. {
  61. t -= Time.deltaTime;
  62. }
  63. else
  64. {
  65. t = delay;
  66. ShiftMaterial( 1 );
  67. }
  68. }
  69. else
  70. {
  71. if ( Input.GetKeyDown( nextKey ) )
  72. ShiftMaterial( 1 );
  73. if ( Input.GetKeyDown( prevKey ) )
  74. ShiftMaterial( -1 );
  75. }
  76. }
  77. }