Unity按钮控制音乐播放(更改代码)

时间:2015-10-29 17:34:29

标签: c# unity3d unity3d-2dtools

我想创建一个按钮播放音乐按钮,但我不明白如何获取按钮并使用它执行功能。除了使音乐停止和开始之外,我还想更改按钮图像以指示音乐是否已启用。这是我的代码:

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");
    }
}

}

所以我把这个脚本放在Button上。 注意我已经更改了我的代码,但现在控制台显示了这个: enter image description here

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来打破。