我想创建一个按钮播放音乐按钮,但我不明白如何获取按钮并使用它执行功能。除了使音乐停止和开始之外,我还想更改按钮图像以指示音乐是否已启用。这是我的代码:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SoundControl : MonoBehaviour {
// Use this for initialization
private Button note;
void Start () {
PlayerPrefs.SetInt ("Music", 1);
note = GetComponent<Button> ();
}
// Update is called once per frame
public Sprite onnote;
public Sprite offnote;
void Update () {
if (PlayerPrefs.GetInt ("Music") == 1) {
note.image.overrideSprite = onnote;
Debug.Log("Button Music equals 1 UPdated");
}
if (PlayerPrefs.GetInt ("Music") == 0) {
note.image.overrideSprite = offnote;
Debug.Log("Button Music equals 0 UPdated");
}
}
public void MakeSound()
{
Debug.Log("Button Music pressed");
if (PlayerPrefs.GetInt ("Music") == 1) {
PlayerPrefs.SetInt ("Music", 0);
Debug.Log("Button Music equals 0");
}
if (PlayerPrefs.GetInt ("Music") == 0) {
PlayerPrefs.SetInt ("Music", 1);
Debug.Log("Button Music equals 1");
}
}
}
答案 0 :(得分:0)
这是我纠正我的代码的方式:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SoundControl : MonoBehaviour {
// Use this for initialization
private Button note;
void Start () {
PlayerPrefs.SetInt ("Music", 1);
note = GetComponent<Button> ();
}
// Update is called once per frame
public Sprite onnote;
public Sprite offnote;
void Update () {
if (PlayerPrefs.GetInt ("Music") == 1) {
note.image.overrideSprite = onnote;
Debug.Log("Button Music equals 1 UPdated");
}
if (PlayerPrefs.GetInt ("Music") == 0) {
note.image.overrideSprite = offnote;
Debug.Log("Button Music equals 0 UPdated");
}
}
public void MakeSound()
{
switch(PlayerPrefs.GetInt("Music"))
{
case 0:
PlayerPrefs.SetInt ("Music", 1);
Debug.Log("Button Music equals 1");
break;
case 1:
PlayerPrefs.SetInt ("Music", 0);
Debug.Log("Button Music equals 0");
break;
}
}
}
当我使用时如果我不能从循环中突然出现:) 所以当我需要的时候我用switch来打破。