我有 10 个附加了文本组件的滑块,它们应该显示滑块值并将值保存到 playerprefs。除了某些文本框在再次播放场景时不会更新/显示其文本之外,这一切都完美无缺。一半的文本框用它们从 playerprefs 中保存的值填充它们的文本值,另一半返回 null,即使它们的值被正确保存。
这是我保存值的代码(附加到每个滑块):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveSliderValue : MonoBehaviour {
public Slider Slider;
public float valueofslider;
void Start()
{
valueofslider = PlayerPrefs.GetFloat(gameObject.name + "valueofslider");
Slider.value = valueofslider;
}
void Update()
{
valueofslider = Slider.value;
if (Input.GetKeyDown(KeyCode.S))
{
PlayerPrefs.SetFloat(gameObject.name + "valueofslider", valueofslider);
Debug.Log("save");
}
}
}
并显示值(附加到每个文本组件)::
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class showvalue : MonoBehaviour {
Text percentageText;
// Use this for initialization
void Start () {
percentageText = GetComponent<Text>();
Debug.Log(percentageText);
}
// Update is called once per frame
public void textUpdate (float value)
{
if (percentageText != null)
percentageText.text = value.ToString();
else
Debug.Log("Variable percentagetext is not set.");
}
}
和错误:
Variable percentagetext is not set.
UnityEngine.Debug:Log(Object)
showvalue:textUpdate(Single) (at Assets/showvalue.cs:24)
UnityEngine.UI.Slider:set_value(Single)
SaveSliderValue:Start() (at Assets/SaveSliderValue.cs:19)
图片 - 用于理解
如果我删除 debug.log 我得到一个空引用。