RandomPrefab.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using DunGen.Pooling;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace DunGen
  5. {
  6. [AddComponentMenu("DunGen/Random Props/Random Prefab")]
  7. public class RandomPrefab : RandomProp, ITileSpawnEventReceiver
  8. {
  9. [AcceptGameObjectTypes(GameObjectFilter.Asset)]
  10. public GameObjectChanceTable Props = new GameObjectChanceTable();
  11. public bool ZeroPosition = true;
  12. public bool ZeroRotation = true;
  13. private GameObject propInstance;
  14. private void ClearExistingInstances()
  15. {
  16. if (propInstance == null)
  17. return;
  18. DestroyImmediate(propInstance);
  19. propInstance = null;
  20. }
  21. public override void Process(RandomStream randomStream, Tile tile, ref List<GameObject> spawnedObjects)
  22. {
  23. ClearExistingInstances();
  24. if (Props.Weights.Count <= 0)
  25. return;
  26. var chosenEntry = Props.GetRandom(randomStream,
  27. tile.Placement.IsOnMainPath,
  28. tile.Placement.NormalizedDepth,
  29. previouslyChosen: null,
  30. allowImmediateRepeats: true,
  31. removeFromTable: false,
  32. allowNullSelection: true);
  33. if (chosenEntry == null || chosenEntry.Value == null)
  34. return;
  35. var prefab = chosenEntry.Value;
  36. propInstance = Instantiate(prefab);
  37. propInstance.transform.parent = transform;
  38. spawnedObjects.Add(propInstance);
  39. if (ZeroPosition)
  40. propInstance.transform.localPosition = Vector3.zero;
  41. else
  42. propInstance.transform.localPosition = prefab.transform.localPosition;
  43. if (ZeroRotation)
  44. propInstance.transform.localRotation = Quaternion.identity;
  45. else
  46. propInstance.transform.localRotation = prefab.transform.localRotation;
  47. }
  48. //
  49. // Begin ITileSpawnEventReceiver implementation
  50. public void OnTileSpawned(Tile tile) { }
  51. public void OnTileDespawned(Tile tile) => ClearExistingInstances();
  52. // End ITileSpawnEventReceiver implementation
  53. //
  54. }
  55. }