到达阵列结束时禁用按钮

时间:2015-07-24 16:45:30

标签: c# arrays button unity3d

如何正确禁用GameObject内的按钮?到目前为止我的代码返回错误:

  

NullReferenceException:未将对象引用设置为的实例   object LoadGallery.nextImage()。

此错误来自以下行:

Button btn = nextBtn.GetComponent<Button>();

我不明白为什么引用无效。还有一种最佳做法是将if-else语句中的重复代码合并到一个位置?

// Increment through gallery
if(currentIndexArray < galleryImages.Length)
{
    StartCoroutine("loader", currentIndexArray++);
}
// Disable Next Button when the end is reached
if(currentIndexArray == galleryImages.Length)
{
    GameObject nextBtn = GameObject.FindGameObjectWithTag("NextBtn");
    Button btn = nextBtn.GetComponent<Button>();
    btn.enabled = false;
    btn.interactable = false;
}
else
{
    GameObject nextBtn = GameObject.FindGameObjectWithTag("NextBtn");
    Button btn = nextBtn.GetComponent<Button>();
    btn.enabled = true;
    btn.interactable = true;
}

3 个答案:

答案 0 :(得分:2)

数组索引为零索引,因此您必须更改

if(currentIndexArray < galleryImages.Length)

if(currentIndexArray < galleryImages.Length - 1)

if (currentIndexArray == galleryImages.Length)

if (currentIndexArray == galleryImages.Length - 1)

答案 1 :(得分:1)

确保nextBtn gameObject在使用方法GetComponent<Button>()之前不为空。

尝试添加如下的空检查:

GameObject nextBtn = GameObject.FindGameObjectWithTag("NextBtn");
if(nextBtn != null)
{
    Button btn = nextBtn.GetComponent<Button>();
    btn.enabled = true;
    btn.interactable = true;
}

答案 2 :(得分:0)

我通过将按钮gameObjects公开来实现它:

public GameObject nextBtn;
public GameObject prevBtn;

然后我将游戏对象放入Unity的Inspector窗口的脚本部分中的各自字段中。之后,我删除了函数中的FindObjectByTag行以及其他所有工作。

public void nextImage()
{
    // Increment through gallery
    if(currentIndexArray < galleryImages.Length)
    {
        StartCoroutine("loader", currentIndexArray++);
        Debug.Log(currentIndexArray);
    }
    // Disable Next Button when the end is reached
    if(currentIndexArray == galleryImages.Length)
    {
        Button btn = nextBtn.GetComponent<Button>();
        btn.enabled = false;
        btn.interactable = false;
    } else {
        Button btn = nextBtn.GetComponent<Button>();
        btn.enabled = true;
        btn.interactable = true;
    }
}

public void prevImage()
{
    // Decrement through gallery
    if(currentIndexArray > 0)
    {
        StartCoroutine("loader", currentIndexArray--);
        Debug.Log(currentIndexArray);
    }
    // Disable Prev Button when the end is reached
    if(currentIndexArray == 0)
    {
        Button btn = nextBtn.GetComponent<Button>();
        btn.enabled = false;
        btn.interactable = false;
    } else {
        Button btn = nextBtn.GetComponent<Button>();
        btn.enabled = true;
        btn.interactable = true;
    }
}