Unity NullReference对不同方法的异常

时间:2018-03-08 05:48:40

标签: c# unity3d

你能帮我发现错误吗?如果我这样做:

private Image ImgPreview;
private Text TxtBrand, TxtProduct, TxtDimentions, TxtDescription, TxtPrice;

// Use this for initialization
void Start () {
    ImgPreview = transform.GetChild(0).GetComponent<Image>();
    TxtProduct = transform.GetChild(1).GetComponent<Text>();
    TxtBrand = transform.GetChild(2).GetComponent<Text>();
    TxtDimentions = transform.GetChild(3).GetComponent<Text>();
    TxtDescription = transform.GetChild(4).GetComponent<Text>();
    TxtPrice = transform.GetChild(5).GetComponent<Text>();

    TxtProduct.text = "test";
}

我的日常工作正常,但如果我这样做:

private Image ImgPreview;
private Text TxtBrand, TxtProduct, TxtDimentions, TxtDescription, TxtPrice;

// Use this for initialization
void Start () {
    ImgPreview = transform.GetChild(0).GetComponent<Image>();
    TxtProduct = transform.GetChild(1).GetComponent<Text>();
    TxtBrand = transform.GetChild(2).GetComponent<Text>();
    TxtDimentions = transform.GetChild(3).GetComponent<Text>();
    TxtDescription = transform.GetChild(4).GetComponent<Text>();
    TxtPrice = transform.GetChild(5).GetComponent<Text>();
}

private IEnumerator GetLogo(string url, int version)
{
    TxtProduct.text = "test";

    WWW www = new WWW(url);
    yield return www;

    ImgPreview.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
}

我收到以下错误:

  

NullReferenceException:未将对象引用设置为对象的实例   ProductBtn.SetInfo(Int32 id,System.String product,System.String category,System.String brand,System.String url,System.String price,System.String coin,System.String width,System.String height,System.String depth,System.String assetobj,System.String assetname,System.String thumbnail,Int32 thumbnailver)(在Assets / Scenes / Product / Scripts / ProductBtn.cs:62)   ProductControl + c__Iterator0.MoveNext()(在Assets / Scenes / Product / Scripts / ProductControl.cs:45)   UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator枚举器,IntPtr returnValueAddress)(在C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

---编辑--- 在进行一些测试后,我意识到将我的文本从&#34; private&#34; 更改为&#34; public&#34; 修复了错误,有人可以解释一下我为什么?我无法理解原因

谢谢......

0 个答案:

没有答案