Reading Assets from folders was only possible in Editor over LoadAssetFromPath. Now I'm using asset bundles for ScriptedObjects and Audio Prefabs, when the project is built. When in Editor the folders are still used for convenience (can make changes to assets without rebuilding asset bundles)
81 lines
2.3 KiB
C#
81 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using log4net;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
|
|
namespace Managers
|
|
{
|
|
/// <summary>
|
|
/// Handles setting up the available character/ship options, which the players can choose from,
|
|
/// connects them to the players when choosen and manages them (spawning, despawning etc.).
|
|
/// </summary>
|
|
public class CharacterManager : MonoBehaviour
|
|
{
|
|
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
|
|
|
|
/// <summary>
|
|
/// Globally accessible member to use manager with.
|
|
/// </summary>
|
|
public static CharacterManager G { get; private set; }
|
|
public List<ShipProperties> AvailableShips { get; private set; } = new List<ShipProperties>();
|
|
private static readonly string characterAssetsBundleName = "characters";
|
|
private static readonly string characterAssetsPath = "Assets/ScriptedAssets/Characters";
|
|
|
|
void Awake()
|
|
{
|
|
G = this;
|
|
Log.Info("Awake");
|
|
}
|
|
|
|
void Start()
|
|
{
|
|
LoadAvailableCharacters();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads the characters a player can choose from a fixed path
|
|
/// in the project.
|
|
/// </summary>
|
|
private void LoadAvailableCharacters()
|
|
{
|
|
#if UNITY_EDITOR
|
|
string[] files = Directory.GetFiles(characterAssetsPath, "*.asset",
|
|
SearchOption.TopDirectoryOnly);
|
|
foreach (var file in files)
|
|
{
|
|
AvailableShips.Add(AssetDatabase.LoadAssetAtPath<ShipProperties>(file));
|
|
}
|
|
#else
|
|
var characterAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, characterAssetsBundleName));
|
|
if (characterAssetBundle == null)
|
|
{
|
|
Log.Error("Failed to load rules asset bundle!");
|
|
return;
|
|
}
|
|
AvailableShips.AddRange(characterAssetBundle.LoadAllAssets<ShipProperties>());
|
|
#endif
|
|
}
|
|
|
|
/// <summary>
|
|
/// Assigns a ship to the player.
|
|
/// Depends on the number of the player.
|
|
/// Player number 2 always gets ship number 2 in the characters folder.
|
|
/// </summary>
|
|
/// <param name="p">Player</param>
|
|
public void AssignShipFixed(Player p)
|
|
{
|
|
if (availableShips.Count >= p.playerNumber)
|
|
{
|
|
p.character = availableShips[p.playerNumber - 1];
|
|
}
|
|
else
|
|
{
|
|
Log.Error($"There was no ship assigned to player number: {p.playerNumber}" +
|
|
" There are not enough ships to choose from.");
|
|
}
|
|
}
|
|
}
|
|
} |