0

我有 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 我得到一个空引用。

在此处输入图像描述

4

2 回答 2

2

Start不能依赖函数的执行顺序。将 showvalueStart函数重命名为Awake,看看是否有帮助。

基本上发生的事情是:

  • 一些showvalue实例Start比它们对应的更早地执行它们的功能SaveSliderValue
  • 因此他们正确设置了文本的值
  • 并且对于某些顺序被破坏(因为 Start 函数以任意顺序执行)=>您的错误

唤醒总是在开始之前执行 - 使用它对您有利。

于 2018-03-27T17:11:34.877 回答
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.");


    }
}
于 2018-03-27T17:43:30.090 回答