【发布时间】:2021-01-18 10:35:04
【问题描述】:
我正在为我目前从事的游戏项目制作角色创建者。我正在使用 Texture2D 作为颜色选择器来选择头发、皮肤的颜色,例如我可以使用 DonDestroyOnLoad 保存它,但我想知道如何将它保存为 PlayerPrefs。我最初是从教程https://www.youtube.com/watch?v=rKhFYxUNL6A&list=PLiW_iGwxIxj_lMxm1UJeGNYJbqZ828UYx&index=2&t=1045s 中获得代码的。原人说可以用ToHtmlStringRGB和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);
}
}
}
}
【问题讨论】: