Création d'un petit party-game anonyme de Build + Bagar sous Unity
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BlockSpawner.cs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5. public class BlockSpawner : MonoBehaviour
  6. {
  7. [SerializeField]
  8. private GameObject _blockToPlace;
  9. public GameObject BlockToPlace
  10. {
  11. get
  12. {
  13. return _blockToPlace;
  14. }
  15. set
  16. {
  17. DisablePreviewMode();
  18. _blockToPlace = value;
  19. }
  20. }
  21. public float spawnDistance = 3f;
  22. public Shader previewShader;
  23. private GameObject _blockInstance;
  24. private bool _isPreview = false;
  25. private Shader _initialShader;
  26. public void OnPlaceBlock()
  27. {
  28. if (!_isPreview) return;
  29. _blockInstance.transform.SetParent(null);
  30. SwitchToDefaultRender();
  31. _blockInstance = null;
  32. DisablePreviewMode();
  33. }
  34. public void OnTogglePreviewMode(InputValue value)
  35. {
  36. float valueAsFloat = value.Get<float>();
  37. if (valueAsFloat == 1f) EnablePreviewMode();
  38. else DisablePreviewMode();
  39. }
  40. private void EnablePreviewMode()
  41. {
  42. if (_blockToPlace == null) return;
  43. Vector3 spawnPos = Vector3.forward * spawnDistance;
  44. _blockInstance = Instantiate(_blockToPlace, spawnPos, Quaternion.identity);
  45. _blockInstance.transform.SetParent(this.transform, false);
  46. _isPreview = true;
  47. SwitchToMeshRender();
  48. }
  49. private void DisablePreviewMode()
  50. {
  51. if (_blockInstance != null) Destroy(_blockInstance);
  52. _isPreview = false;
  53. }
  54. private void SwitchToMeshRender()
  55. {
  56. MeshRenderer vRenderer = _blockInstance.GetComponent<MeshRenderer>();
  57. Material vMaterial = vRenderer.material;
  58. _initialShader = vMaterial.shader;
  59. vMaterial.shader = previewShader;
  60. }
  61. private void SwitchToDefaultRender()
  62. {
  63. MeshRenderer vRenderer = _blockInstance.GetComponent<MeshRenderer>();
  64. Material vMaterial = vRenderer.material;
  65. vMaterial.shader = _initialShader;
  66. }
  67. }