MB_SwitchBakedObjectsTexture.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class MB_SwitchBakedObjectsTexture : MonoBehaviour {
  5. // The target renderer where we will switch materials.
  6. public MeshRenderer targetRenderer;
  7. // The list of materials to cycle through.
  8. public Material[] materials;
  9. // The Mesh Baker that will do the baking
  10. public MB3_MeshBaker meshBaker;
  11. public void OnGUI()
  12. {
  13. GUILayout.Label("Press space to switch the material on one of the cubes. " +
  14. "This scene reuses the Texture Bake Result from the SceneBasic example.");
  15. }
  16. public void Start()
  17. {
  18. // Bake the mesh.
  19. meshBaker.AddDeleteGameObjects(meshBaker.GetObjectsToCombine().ToArray(),null,true);
  20. meshBaker.Apply();
  21. }
  22. public void Update()
  23. {
  24. if (Input.GetKeyDown(KeyCode.Space))
  25. {
  26. // Cycle the material on targetRenderer to the next material in materials.
  27. Material mat = targetRenderer.sharedMaterial;
  28. //Find the index of the current material on the Renderer
  29. int materialIdx = -1;
  30. for (int i = 0; i < materials.Length; i++){
  31. if (materials[i] == mat){
  32. materialIdx = i;
  33. }
  34. }
  35. // Get the next material in the cycle.
  36. materialIdx++;
  37. if (materialIdx >= materials.Length) materialIdx = 0;
  38. if (materialIdx != -1)
  39. {
  40. // Assign the material to the disabled renderer
  41. targetRenderer.sharedMaterial = materials[materialIdx];
  42. Debug.Log("Updating Material to: " + targetRenderer.sharedMaterial);
  43. // Update the Mesh Baker combined mesh
  44. GameObject[] gameObjects = new GameObject[] { targetRenderer.gameObject };
  45. meshBaker.UpdateGameObjects(gameObjects, false, false, false, false, true, false, false, false, false);
  46. // We could have used AddDelteGameObjects instead of UpdateGameObjects.
  47. // UpdateGameObjects is faster, but does not work if the material change causes
  48. // the object to switch submeshes in the combined mesh.
  49. // meshBaker.AddDeleteGameObjects(gameObjects, gameObjects,false);
  50. // Apply the changes.
  51. meshBaker.Apply();
  52. }
  53. }
  54. }
  55. }