使用Button的ScrollView(NGUI C#UNITY)

时间:2018-06-26 09:42:01

标签: c# unity3d scrollview ngui

我在实现将按钮滑动到我正在使用NGUI的下一页的按钮时遇到问题

这是我的剧本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NGUI_PageNavigation : MonoBehaviour {

public GameObject sv;
public SpringPanel sp = null;
int xSpring = 1278;
// Use this for initialization
void Start()
{
    sp = sv.GetComponent<SpringPanel>();
    if (sp == null) sv.AddComponent<SpringPanel>();

}

private void OnStoppedMoving()
{

    int pagewidth = 320;
    int pageposition = (int)sp.target.x;
    int page = System.Math.Abs(pageposition / pagewidth) + 1;

    print("page " + (page));
}


public void LeftArrow()
{

    sp.target.x = 1278;
    sp.target.y = 0;
    sp.target.z = 0;
    sp.target = new Vector3(sp.target.x, sp.target.y, sp.target.z);
    sp.enabled = true;

    //Debug.Log("I've been clicked - Left Arrow()");
}

public void RightArrow()
{
    sp.target.x = -1278;
    sp.target.y = 0;
    sp.target.z = 0;
    sp.target = new Vector3(sp.target.x,sp.target.y,sp.target.z);
    sp.enabled = true;
    //Debug.Log("I've been cliked - Right Arrow()");
}
}

  

NullReferenceException:在需要对象实例的地方找到了空值。

有人可以帮助我

1 个答案:

答案 0 :(得分:1)

看一下这段代码:

void Start()
{
    sp = sv.GetComponent<SpringPanel>();
    if (sp == null) sv.AddComponent<SpringPanel>();
}

如果GetComponent由于null未附加到SpringPanel GameObject而返回sv,则SpringPanel组件将被添加到sv游戏对象。问题是sp仍将是null。您还应该将AddComponent返回的值分配给sp

替换

if (sp == null) 
    sv.AddComponent<SpringPanel>();

使用

if (sp == null) 
    sp = sv.AddComponent<SpringPanel>();