Unity c#如何将颜色纹理保存为playerprefs



我正在为我目前正在从事的游戏项目制作角色创造者。我使用Texture2D作为一个颜色选择器,用于挑选头发,皮肤的颜色,例如,我可以使用DonDestroyOnLoad保存它,但我想知道如何将其保存为PlayerPrefs。我最初从教程https://www.youtube.com/watch?v=rKhFYxUNL6A&list=PLiW_iGwxIxj_lMxm1UJeGNYJbqZ828UYx&index=2&t=1045s获得了代码。原来的人说,我可以使用tohtmlstringgrgb和TryParseHtmlString,但我不知道如何实现它到脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
using UnityEngine.Events;
[Serializable]
public class ColorEvent : UnityEvent<Color> { }
public class ColourPicker : MonoBehaviour
{
public TextMeshProUGUI DebugText;
public ColorEvent OnColorPreview;
public ColorEvent OnColorSelect;
RectTransform Rect;
Texture2D ColorTexture;

void Start()
{
Rect = GetComponent<RectTransform>();
ColorTexture = GetComponent<Image>().mainTexture as Texture2D;
}

void Update()
{
if (RectTransformUtility.RectangleContainsScreenPoint(Rect, Input.mousePosition))
{
Vector2 delta;
RectTransformUtility.ScreenPointToLocalPointInRectangle(Rect, Input.mousePosition, null, out delta);
string debug = "mousePosition=" + Input.mousePosition;
debug += "<br>delta" + delta;
float width = Rect.rect.width;
float height = Rect.rect.height;
delta += new Vector2(width * .5f, height * .5f);
debug += "<br>offset delta" + delta;
float x = Mathf.Clamp(delta.x / width, 0f, 1f);
float y = Mathf.Clamp(delta.y / height, 0f, 1f);
debug += "<br>x=" + x + " y=" + y;
int texX = Mathf.RoundToInt(x * ColorTexture.width);
int texY = Mathf.RoundToInt(y * ColorTexture.height);
debug += "<br>texX=" + texX + " texY=" + texY;
Color color = ColorTexture.GetPixel(texX, texY);
DebugText.color = color;
DebugText.text = debug;

OnColorPreview?.Invoke(color);
if (Input.GetMouseButtonDown(0))
{
OnColorSelect?.Invoke(color);
}

}
}
}

首先,您需要将颜色转换为字符串并保存到PlayerPrefs:

var colorHexCode = ColorUtility.ToHtmlStringRGBA(color);
PlayerPrefs.SetString("CharacterColor", colorHexCode);

然后,你可以像这样从PlayerPrefs中获得颜色的HTML字符串值:

var colorHexCode = PlayerPrefs.GetString("CharacterColor");

并转换为Color:

Color color = Color.black;
if(ColorUtility.TryParseHtmlString(colorHexCode, out color))
{
// Do something if color parsing is successful
}

最新更新