Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Last active June 7, 2021 08:50
Show Gist options
  • Save unity3dcollege/20dfaadc09fe93eb87d23f7a0682cbd0 to your computer and use it in GitHub Desktop.
Save unity3dcollege/20dfaadc09fe93eb87d23f7a0682cbd0 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class GameDataController : MonoBehaviour
{
public static SaveData saveData;
private void Awake()
{
LoadData();
}
[ContextMenu("Save Data")]
public void SaveGame()
{
var data = JsonUtility.ToJson(saveData);
PlayerPrefs.SetString("GameData", data);
}
[ContextMenu("Load Data")]
public void LoadData()
{
var data = PlayerPrefs.GetString("GameData");
saveData = JsonUtility.FromJson<SaveData>(data);
}
private void OnDisable()
{
SaveGame();
}
public static bool GetState(MagicCube magicCube)
{
if (saveData.magicCubes == null)
return false;
if (saveData.magicCubes.Any(t => t.id == magicCube.name))
return saveData.magicCubes.FirstOrDefault(t => t.id == magicCube.name).isRed;
return false;
}
public static void SetState(MagicCube magicCube, bool isRed)
{
if (saveData.magicCubes == null)
saveData.magicCubes = new List<MagicCubeData>();
var magicCubeData = new MagicCubeData() { id = magicCube.name, isRed = isRed };
saveData.magicCubes.RemoveAll(t => t.id == magicCubeData.id);
saveData.magicCubes.Add(magicCubeData);
}
}
using UnityEngine;
public class MagicCube : MonoBehaviour
{
public bool IsRed { get; set; }
private void Start()
{
IsRed = GameDataController.GetState(this);
UpdateColor();
}
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (GetComponent<Collider>().Raycast(ray, out hitInfo, Mathf.Infinity))
{
IsRed = !IsRed;
UpdateColor();
GameDataController.SetState(this, IsRed);
}
}
}
private void UpdateColor()
{
GetComponent<MeshRenderer>().material.color = IsRed ? Color.red : Color.green;
}
}
using System;
using System.Collections.Generic;
[Serializable]
public struct SaveData
{
public int currentHealth;
public int lastLevelBeat;
public List<MagicCubeData> magicCubes;
}
[Serializable]
public struct MagicCubeData
{
public string id;
public bool isRed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment