我有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,我会得到一个空引用。
答案 0 :(得分:2)
不能依赖Start
函数的执行顺序。将showvalue Start
函数重命名为Awake
,看看是否有帮助。
基本上会发生什么:
showvalue
个实例比相应的Start
SaveSliderValue
个功能
在开始之前总是执行唤醒 - 使用它对您有利。
答案 1 :(得分:0)
这里的ShowValues脚本的工作代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class showvalue : MonoBehaviour {
Text percentageText;
// Use this for initialization
void Awake () {
percentageText = GetComponent<Text>();
//percentageText = GameObject.Find("ThePlayer").GetComponent<SaveSliderValue>().valueofslider;
}
// 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.");
}
}