我在实现按钮以滑动到下一页时遇到问题 我正在使用 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:在需要对象实例的位置找到 null 值。
有人可以帮助我吗
看看你的代码的这一部分:
void Start()
{
sp = sv.GetComponent<SpringPanel>();
if (sp == null) sv.AddComponent<SpringPanel>();
}
如果GetComponent
返回null
SpringPanel
未附加到sv
游戏对象,则SpringPanel
组件将添加到sv
游戏对象中。问题是sp
仍然会null
.还应将AddComponent
返回的值分配给sp
。
取代
if (sp == null)
sv.AddComponent<SpringPanel>();
跟
if (sp == null)
sp = sv.AddComponent<SpringPanel>();