PJ/Assets/scripts/LevelCreatorHelper.cs

233 lines
No EOL
7 KiB
C#

using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using TMPro.Examples;
using TMPro;
using System.Security.Cryptography; // Нужно добавить для хеша
using System.Text;
public class LevelCreatorHelper : MonoBehaviour
{
private int NewBlock = 1;
private int SelectSet;
private int BlockID = 1;
public GameObject CPlayer;
private Vector2 Pos;
public GameObject DestroyBlock;
public GameObject NewDest;
public GameObject[] Block;
public List<Rtool> Bl;
private List<string> BlockData = new List<string> {};
public GameObject Map;
private int HSizeY;
private int HSizeX;
public GameObject Mapc;
private RectTransform sz;
public string LevelName;
public string version;
public string file;
public GameObject Test;
public GameObject TestPlayer;
public GameObject OtherScreen;
List<GameObject> objects = new List<GameObject> { };
[SerializeField] public GameObject Pobject;
public GameObject ObjectsToSave;
private object OTS;
public GameObject center;
public GameObject RU;
public TMP_Text ST;
public Slider Zoom;
private void Start()
{
if (GameObject.Find("Tobj") != null)
file = GameObject.Find("Tobj").GetComponent<TransferScript>().string1;
sz = Mapc.GetComponent<RectTransform>();
ST.text = "Path to save or load:" + Application.persistentDataPath + "/";
if (file.Length > 0)
print("notnull");
}
private void Update()
{
switch (SelectSet)
{
case 1:
if (Input.GetMouseButtonDown(0))
{
Pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Pos.y > -2)
{
Debug.Log(NewBlock);
//Debug.Log(Bl.Count);
Debug.Log(BlockID);
Bl.Add(Instantiate(Block[NewBlock].GetComponent<Rtool>()));
Bl[BlockID].transform.position = new Vector3(Pos.x, Pos.y, ObjectsToSave.transform.position.z);
Bl[BlockID].transform.SetParent(ObjectsToSave.transform);
Bl[BlockID].transform.localScale = new Vector3 (1,1,1) /GameObject.Find("Canvas (1)").transform.localScale.x;
Debug.Log(BlockID);
BlockID++;
}
}
break;
case 2:
if (Input.GetMouseButtonDown(0))
{
Pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Pos.y > 5)
{
NewDest = Instantiate(DestroyBlock);
NewDest.transform.position = (Pos + new Vector2(11, 4.5f)) * 50;
NewDest.SetActive(true);
}
}
break;
}
}
public void CameraZoom()
{
Map.transform.localScale = new Vector3(1,1,1) / Zoom.value;
}
public void StartTest()
{
Test.SetActive(true);
TestPlayer.transform.position = CPlayer.transform.position;
print(CPlayer.transform.position);
print(TestPlayer.transform.position);
CPlayer.SetActive(false);
OtherScreen.SetActive(false);
}
public void FishTest()
{
Test.SetActive(false);
CPlayer.SetActive(true);
OtherScreen.SetActive(true);
}
public void Desel()
{
SelectSet = 0;
}
public void NewBlockID(int ID)
{
SelectSet = 1;
NewBlock = ID;
}
public void Dest()
{
SelectSet = 2;
}
public void SizeX(string x)
{
HSizeX = int.Parse(x);
}
public void SizeY(string y)
{
HSizeY = int.Parse(y);
}
public void Size()
{
sz.sizeDelta = new Vector2(HSizeX, HSizeY);
}
public void SetName(string name)
{
LevelName = name;
}
public byte[] ListToBytes<T>(List<T> list)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, list);
return stream.ToArray();
}
}
public void SaveLevel()
{
BlockData.Clear();
// 1. ПЕРВЫМ делом добавляем имя уровня в список данных
List<string> meta = new List<string> {LevelName, version};
BlockData.Add(LevelName);
for (int i = 0; i != ObjectsToSave.GetComponentsInChildren<Rtool>().Length; i++)
{
Rtool o = ObjectsToSave.GetComponentsInChildren<Rtool>()[i];
List<float> TBD = new List<float> { };
TBD.Add(o.pos.x*Zoom.value);//0
TBD.Add(o.pos.y*Zoom.value);//1
TBD.Add(o.pos.z*Zoom.value);//2
TBD.Add(o.rot.x);//3
TBD.Add(o.rot.y);//4
TBD.Add(o.rot.z);//5
TBD.Add(o.rot.w);//6
TBD.Add(o.BlockID);//7
TBD.Add(o.pos1.x*Zoom.value);//8
TBD.Add(o.pos1.y*Zoom.value);//9
TBD.Add(o.pos1.z*Zoom.value);//10
TBD.AddRange(new List<float> {o.values[0],o.values[1],o.values[2],o.values[3]});//11, 12, 13, 14
BlockData.Add(string.Join(", ",TBD));
TBD.Clear();
}
SavingLevel();
}
public void SavingLevel()
{
//Vector3 BackSize = Map.transform.localScale;
//Map.transform.localScale = new Vector3(1,1,1);
try
{
// 1. Сначала превращаем данные в байты
byte[] data = ListToBytes(BlockData);
// 2. Считаем хеш от этих байтов
string fileHash = file.Length > 0 ? file : GetSHA256Hash(data);
// 3. Формируем путь, используя Хеш вместо LevelName
string correctPath = Path.Combine(Application.persistentDataPath, $"{fileHash}.lpj");
// 4. Сохраняем
File.WriteAllBytes(correctPath, data);
Debug.Log($"Successfully saved with Hash name: {correctPath}");
}
catch (System.Exception e)
{
Debug.LogError($"Save failed: {e.Message}");
}
//Map.transform.localScale = BackSize;
}
// Функция для генерации хеша
private string GetSHA256Hash(byte[] data)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(data);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2")); // Переводим в строку типа a1b2c3...
}
return sb.ToString();
}
}
}