3DTD/Assets/Scripts/PlacementSystem/PlacementManager.cs

99 lines
2.7 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
public class TowerPlacementManager : MonoBehaviour
{
/// <summary>
/// Sender
/// </summary>
public static event Action<TowerPlacementManager> OnSpawnGridRequested;
public static TowerPlacementManager Singleton;
// Section: Selection
private SlotManager CurrentSelected;
// Section: Debug
public GameObject DebugTowerPrefab;
private bool IsPlacing = true; // Show silluette or nothing
private void Start()
{
if (Singleton != this)
Destroy(Singleton);
Singleton = this;
OnSpawnGridRequested?.Invoke(this);
ToSilhouette(DebugTowerPrefab);
}
public void OnSlotClicked(SlotManager slot, GridManager grid, int x, int y)
{
slot.gameObject.GetComponentInChildren<Renderer>().material.color = Color.blue;
OnSelectSlot(slot);
SpawnTowerAtSelected(DebugTowerPrefab);
}
// Called when a slot is selected
public void OnSelectSlot(SlotManager slot)
{
// Detects if the selected slot is new
if (CurrentSelected != null && CurrentSelected != slot)
OnDeselectSlot(CurrentSelected, slot);
CurrentSelected = slot;
slot.gameObject.GetComponentInChildren<Renderer>().material.color = Color.blue;
}
// Called when another slot is getting selected
public void OnDeselectSlot(SlotManager prevSlot, SlotManager newSlot)
{
prevSlot.gameObject.GetComponentInChildren<Renderer>().material.color = Color.white;
}
public void SpawnTowerAtSelected(GameObject towerPrefab)
{
Instantiate(towerPrefab, CurrentSelected.transform);
}
public void OnSlotHovered()
{
}
[Space(10)]
public Material SilhouetteMaterial;
public GameObject ToSilhouette(GameObject obj)
{
// if prefab, then spawn it
if (obj.scene.name == null)
obj = Instantiate(obj);
Component[] objScripts = obj.GetComponents<Component>();
objScripts = objScripts.Concat(obj.GetComponentsInChildren<Component>()).ToArray();
for (int i = 0; i < objScripts.Length; i++)
{
var comp = objScripts[i];
if (comp is not Renderer && comp is not Transform && comp is not MeshFilter)
{
Destroy(comp);
}
else if (typeof(Renderer).IsAssignableFrom(comp))
{
var renderer = comp as Renderer;
renderer.materials = new Material[] { SilhouetteMaterial , SilhouetteMaterial , SilhouetteMaterial , SilhouetteMaterial , SilhouetteMaterial };
}
}
return obj;
}
}