PJ/Assets/scripts/LevelImport.cs

239 lines
9.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using System.IO;
using JetBrains.Annotations;
using System;
using System.Linq;
using System.Globalization;
public class LevelImport : MonoBehaviour
{
public static event Action<string> OnLevelLoaded;
string LName;
public List<GameObject> Blocks;
public GameObject[] BlockType;
public List<string> BlockData;
public Transform map;
public GameObject[] HelpObjects;
[SerializeField] Transform MapP;
[SerializeField] LevelCreatorHelper lch;
string name;
// Start is called before the first frame update
void Start()
{
GameObject tobj = GameObject.Find("Tobj");
if (tobj != null)
{
LName = tobj.GetComponent<TransferScript>().string1;
print("Loaded Level:" + LName);
Import();
// Удаляем ТОЛЬКО ПОСЛЕ того, как Import полностью отработал
Destroy(tobj);
}
}
public void SetName(string Name)
{
LName = Name;
}
public void Import()
{
// 1. Пытаемся загрузить данные (сначала диск, потом ресурсы)
try
{
string correctPath = Path.Combine(Application.persistentDataPath, $"{LName}.lpj");
byte[] BA;
if (File.Exists(correctPath)) {
BA = File.ReadAllBytes(correctPath);
}
else if (File.Exists(correctPath + "l")) {
BA = File.ReadAllBytes(correctPath + "l");
}
else {
// Если на диске нет, грузим из Resources
BA = Resources.Load<TextAsset>("Levels/" + LName).bytes;
}
BlockData = ConvertFromByteArray(BA);
}
catch (Exception e)
{
Debug.LogError("Ошибка загрузки данных: " + e.Message);
return; // Если данных нет, дальше идти нельзя
}
// 2. ДАННЫЕ ПОЛУЧЕНЫ. Теперь извлекаем имя и оповещаем всех
if (BlockData != null && BlockData.Count > 0)
{
name = BlockData[0];
OnLevelLoaded?.Invoke(name);
}
// 3. Дальше твой старый код спавна (циклы for и т.д.)
print(BlockData.Count);
foreach(string b in BlockData)
{print(b);}
name = BlockData[0];
if (GameObject.Find("PlayerSpawn") == null)
{
for (int i = 1; i != BlockData.Count; i++)
{
List<float> Data;
try
{
Data = StringToIntList(BlockData[i]);
}
catch
{
Data = BlockData[i].Split(", ")
.Select(s => float.Parse(s.Trim(), CultureInfo.InvariantCulture))
.ToList();
}
print(string.Join(", ", Data));
GameObject NB = Instantiate(BlockType[(int)Data[7]], new Vector3(Data[0], Data[1], Data[2]), new Quaternion(Data[3], Data[4], Data[5], Data[6]), map);
Blocks.Add(NB);
if (Data[7] > 2 || Data[7] ==0)
{
switch(Data[7])
{
case 0:
Move pd = GameObject.Find("player").GetComponent<Move>();
pd.NormalSpeed = Data[11];
pd.jumpforce = Data[12];
//pd.LVLMusic = mus[Data[13]];
Camx camx = Camera.main.GetComponent<Camx>();
pd.numlvl = LName;
print(LName + pd.numlvl);
switch (Data[14])
{
case 1:
camx.x = true;
break;
case 2:
camx.y = true;
break;
case 3:
camx.y = true;
camx.x = true;
break;
}
break;
case 3:
if (!string.IsNullOrEmpty(LName))
{
string numberPart = LName.Replace("Level", "");
if (int.TryParse(numberPart, out int levelIndex))
{
NB.GetComponent<NextLevel>().ThisLevel = levelIndex;
NB.GetComponent<NextLevel>().IsMiniGame = false;
}
}
break;
break;
case 5:
NB.GetComponent<IceBlock>().IceStrength = (int)Data[11];
break;
case 7:
BubbleBlock bd = NB.GetComponent<BubbleBlock>();
bd.TimeUp = Data[11];
bd.Speed = Data[12];
break;
case 10:
TPBlock td = NB.GetComponent<TPBlock>();
td.SecondTeleport = Instantiate(HelpObjects[0], new Vector3(Data[8], Data[9], Data[10]) - MapP.position, new Quaternion(0,0,0,0));
break;
case 11:
Items item = NB.GetComponent<Items>();
item.time = Data[11];
item.id = (int)Data[12];
break;
case 12:
NB.transform.localScale = new Vector3(3,3,3);
break;
case 13:
NB.transform.localScale = new Vector3(3,3,3);
break;
case 15:
EnityControl EC = NB.GetComponent<EnityControl>();
EC.MinDamage = (int)Data[8];
EC.MaxDamage = (int)Data[9];
EC.Speed = (int)Data[10];
EC.Lives = (int)Data[11];
EC.Money = Instantiate(HelpObjects[(int)Data[12]+1]);
EC.PatrolDistance = Data[13];
break;
}
}
Data.Clear();
}
}
else
{
print(BlockData[0]);
lch.LevelName = BlockData[0];
for (int i = 2; i != BlockData.Count; i++)
{
List<float> Data;
try
{
Data = StringToIntList(BlockData[i]);
}
catch
{
Data = BlockData[i].Split(", ")
.Select(s => float.Parse(s.Trim(), CultureInfo.InvariantCulture))
.ToList();
}
print(string.Join(", ", Data));
GameObject NB = Instantiate(BlockType[(int)Data[7]], new Vector3(Data[0], Data[1], Data[2]) + map.position, new Quaternion(Data[3], Data[4], Data[5], Data[6]), map);
NB.transform.localScale = new Vector3 (1,1,1) /GameObject.Find("Canvas (1)").transform.localScale.x;
Rtool rt = NB.GetComponent<Rtool>();
rt.values = new List<float>{Data[11], Data[12], Data[13], Data[14]};
rt.pos1 = new Vector3(Data[8], Data[9], Data[10]);
Blocks.Add(NB);
}
}
}
public static List<string> ConvertFromByteArray(byte[] byteArray)
{
if (byteArray == null || byteArray.Length == 0)
return new List<string>();
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream(byteArray))
{
return (List<string>)formatter.Deserialize(stream);
}
}
public static List<float> StringToIntList(string data, string delimiter = ", ")
{
if (string.IsNullOrEmpty(data))
return new List<float>();
return data.Split(delimiter)
.Where(x => !string.IsNullOrEmpty(x))
.Select(float.Parse)
.ToList();
}
// Update is called once per frame
void Update()
{
}
}