SurroundCaptureDemo.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. //-----------------------------------------------------------------------------
  4. // Copyright 2012-2022 RenderHeads Ltd. All rights reserved.
  5. //-----------------------------------------------------------------------------
  6. namespace RenderHeads.Media.AVProMovieCapture.Demos
  7. {
  8. /// <summary>
  9. /// Spawns cube prefabs from a transform and removes them once they reach a maximum number
  10. /// </summary>
  11. public class SurroundCaptureDemo : MonoBehaviour
  12. {
  13. [SerializeField] Transform _spawnPoint = null;
  14. [SerializeField] GameObject _cubePrefab = null;
  15. [SerializeField] bool _spawn = true;
  16. private const int MaxCubes = 48;
  17. private const float SpawnTime = 0.25f;
  18. // State
  19. private float _timer = SpawnTime;
  20. private List<GameObject> _cubes = new List<GameObject>(32);
  21. private void Update()
  22. {
  23. // Spawn cubes at a certain rate
  24. _timer -= Time.deltaTime;
  25. if (_timer <= 0f)
  26. {
  27. if (_spawn)
  28. {
  29. _timer = SpawnTime;
  30. SpawnCube();
  31. }
  32. // Remove cubes when there are too many
  33. if (_cubes.Count > MaxCubes || !_spawn)
  34. {
  35. RemoveCube();
  36. }
  37. }
  38. }
  39. private void SpawnCube()
  40. {
  41. Quaternion rotation = Quaternion.Euler(Random.Range(-180f, 180f), Random.Range(-180f, 180f), Random.Range(-180f, 180f));
  42. float scale = Random.Range(0.1f, 0.6f);
  43. GameObject go = (GameObject)GameObject.Instantiate(_cubePrefab, _spawnPoint.position, rotation);
  44. Transform t = go.GetComponent<Transform>();
  45. go.GetComponent<Rigidbody>().AddExplosionForce(10f, _spawnPoint.position, 5f, 0f, ForceMode.Impulse);
  46. //AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier = 0.0F, ForceMode mode = ForceMode.Force);
  47. t.localScale = new Vector3(scale * 2f, scale, scale * 2f);
  48. t.SetParent(_spawnPoint);
  49. _cubes.Add(go);
  50. }
  51. private void RemoveCube()
  52. {
  53. if (_cubes.Count > 0)
  54. {
  55. // Remove the oldest cube
  56. GameObject go = _cubes[0];
  57. // Disabling the collider makes it fall through the floor - which is a neat way to hide its removal
  58. go.GetComponent<Collider>().enabled = false;
  59. _cubes.RemoveAt(0);
  60. StartCoroutine("KillCube", go);
  61. }
  62. }
  63. private System.Collections.IEnumerator KillCube(GameObject go)
  64. {
  65. yield return new WaitForSeconds(1.5f);
  66. Destroy(go);
  67. }
  68. }
  69. }