MB_DynamicAddDeleteExample.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class MB_DynamicAddDeleteExample : MonoBehaviour {
  5. public GameObject prefab;
  6. List<GameObject> objsInCombined = new List<GameObject>();
  7. MB3_MultiMeshBaker mbd;
  8. GameObject[] objs;
  9. float GaussianValue(){
  10. float x1, x2, w, y1;
  11. do {
  12. x1 = 2.0f * Random.Range(0f,1f) - 1.0f;
  13. x2 = 2.0f * Random.Range(0f,1f) - 1.0f;
  14. w = x1 * x1 + x2 * x2;
  15. } while ( w >= 1.0f );
  16. w = Mathf.Sqrt( (-2.0f * Mathf.Log( w ) ) / w );
  17. y1 = x1 * w;
  18. return y1;
  19. }
  20. void Start(){
  21. mbd = GetComponentInChildren<MB3_MultiMeshBaker>();
  22. // instantiate game objects
  23. int dim = 10;
  24. GameObject[] gos = new GameObject[dim * dim];
  25. for (int i = 0; i < dim; i++){
  26. for (int j = 0; j < dim; j++){
  27. GameObject go = (GameObject) Instantiate(prefab);
  28. gos[i*dim + j] = go.GetComponentInChildren<MeshRenderer>().gameObject;
  29. float randx = Random.Range(-4f,4f);
  30. float randz = Random.Range(-4f,4f);
  31. go.transform.position = (new Vector3(3f*i + randx, 0, 3f * j + randz));
  32. float randrot = Random.Range (0,360);
  33. go.transform.rotation = Quaternion.Euler(0,randrot,0);
  34. Vector3 randscale = Vector3.one + Vector3.one * GaussianValue() * .15f;
  35. go.transform.localScale = randscale;
  36. //put every third object in a list so we can add and delete it later
  37. if ((i*dim + j) % 3 == 0){
  38. objsInCombined.Add(gos[i*dim + j]);
  39. }
  40. }
  41. }
  42. //add objects to combined mesh
  43. mbd.AddDeleteGameObjects(gos, null, true);
  44. mbd.Apply();
  45. objs = objsInCombined.ToArray();
  46. //start routine which will periodically add and delete objects
  47. StartCoroutine(largeNumber());
  48. }
  49. IEnumerator largeNumber() {
  50. while(true){
  51. yield return new WaitForSeconds(1.5f);
  52. //Delete every third object
  53. mbd.AddDeleteGameObjects(null, objs, true);
  54. mbd.Apply();
  55. yield return new WaitForSeconds(1.5f);
  56. //Add objects back
  57. mbd.AddDeleteGameObjects(objs, null, true);
  58. mbd.Apply();
  59. }
  60. }
  61. void OnGUI(){
  62. GUILayout.Label ("Dynamically instantiates game objects. \nRepeatedly adds and removes some of them\n from the combined mesh.");
  63. }
  64. }