123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.InputSystem;
-
- public class BlockSpawner : MonoBehaviour
- {
-
- [SerializeField]
- private GameObject _blockToPlace;
- public GameObject BlockToPlace
- {
- get
- {
- return _blockToPlace;
- }
- set
- {
- DisablePreviewMode();
- _blockToPlace = value;
- }
- }
-
- public float spawnDistance = 3f;
-
- public Shader previewShader;
- private GameObject _blockInstance;
-
-
- private bool _isPreview = false;
- private Shader _initialShader;
-
- public void OnPlaceBlock()
- {
- if (!_isPreview) return;
- _blockInstance.transform.SetParent(null);
- SwitchToDefaultRender();
- _blockInstance = null;
- DisablePreviewMode();
- }
-
- public void OnTogglePreviewMode(InputValue value)
- {
- float valueAsFloat = value.Get<float>();
-
- if (valueAsFloat == 1f) EnablePreviewMode();
- else DisablePreviewMode();
- }
-
- private void EnablePreviewMode()
- {
- if (_blockToPlace == null) return;
-
- Vector3 spawnPos = Vector3.forward * spawnDistance;
- _blockInstance = Instantiate(_blockToPlace, spawnPos, Quaternion.identity);
- _blockInstance.transform.SetParent(this.transform, false);
- _isPreview = true;
- SwitchToMeshRender();
- }
-
- private void DisablePreviewMode()
- {
- if (_blockInstance != null) Destroy(_blockInstance);
- _isPreview = false;
- }
-
- private void SwitchToMeshRender()
- {
- MeshRenderer vRenderer = _blockInstance.GetComponent<MeshRenderer>();
- Material vMaterial = vRenderer.material;
- _initialShader = vMaterial.shader;
- vMaterial.shader = previewShader;
- }
-
- private void SwitchToDefaultRender()
- {
- MeshRenderer vRenderer = _blockInstance.GetComponent<MeshRenderer>();
- Material vMaterial = vRenderer.material;
- vMaterial.shader = _initialShader;
- }
- }
|