evershade/Assets/Scripts/Managers/InteractableManager.cs

95 lines
3.1 KiB
C#

using System.Linq;
using Data.ScriptableObjects.World;
using UnityEngine;
using Utils;
public class InteractableManager : MonoBehaviour
{
public Interactable[] interactables;
public static InteractableManager Instance { get; private set; }
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
LoadInteractable();
}
else
{
Destroy(gameObject);
}
}
public ScriptableObject GetInteractableByName(string name)
{
foreach (var interactable in interactables)
if (interactable.objectName == name)
return Instantiate((ScriptableObject)interactable);
return null;
}
public ScriptableObject GetInteractableById(int id)
{
foreach (var interactable in interactables)
if (interactable.id == id)
return Instantiate((ScriptableObject)interactable);
return null;
}
public ScriptableObject GetRandomInteractable()
{
if (interactables.Length == 0)
{
GameLogger.LogWarning("No interactable found");
return null;
}
return Instantiate((ScriptableObject)interactables[Random.Range(0, interactables.Length - 1)]);
}
public CropInteractable GetRandomCropInteractable()
{
if (interactables.Length == 0)
{
GameLogger.LogWarning("No interactable found");
return null;
}
GameLogger.Log("Length of interactables: " + interactables.Length);
var cropInteractables = interactables.OfType<CropInteractable>().ToArray();
GameLogger.Log("Length of cropInteractables: " + cropInteractables.Length);
var randomRange = Random.Range(0, cropInteractables.Length - 1);
GameLogger.Log("Random Chosen in range:" + randomRange);
var cropInteractable = cropInteractables[randomRange];
GameLogger.Log("Random Crop Interactable: " + cropInteractable.ObjectName);
return Instantiate(cropInteractables[randomRange]);
}
public IInteractable GetRandomInteractableOfType(InteractableType type)
{
if (interactables.Length == 0)
{
GameLogger.LogWarning("No interactable found");
return null;
}
var interactablesOfType = interactables.Where(i => i.type == type).ToArray();
return Instantiate(interactablesOfType[Random.Range(0, interactablesOfType.Length - 1)]);
}
public void LoadInteractable()
{
GameLogger.Log("Loading interactable from Resources/Interactable");
interactables = Resources.LoadAll<Interactable>("Interactables");
// interactables = interactables.Concat(Resources.LoadAll<TreeInteractable>("Interactables")).ToArray();
// interactables = interactables.Concat(Resources.LoadAll<RockInteractable>("Interactables")).ToArray();
// interactables = interactables.Concat(Resources.LoadAll<BoxInteractable>("Interactables")).ToArray();
/*foreach (var interactable in interactables) GameLogger.Log("Loaded interactable: " + interactable.id);*/
}
}