2017-04-21 160 views
-2

設置UI圖像的情況下我一直有問題,我下面的腳本設置UI圖像的一個實例:不能在腳本

using UnityEngine; 
using UnityEngine.UI; 
using System.Collections; 
using Image = UnityEngine.UI.Image; 
using UnityEngine.UI; 

public class changeimage : MonoBehaviour 
{ 
    public UnityEngine.UI.Image imageobject; 
    // public Sprite myFirstImage; 
    Sprite myFruit = Resources.Load("watermalon", typeof(Sprite)) as Sprite; 

    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 

    } 

    public void ClickToChange2() 
    { 
     //imageobject = GetComponent<Image>(); 
     //Debug.Log(imageobject); 
     imageobject.sprite = myFruit; 
    } 
} 

錯誤是:空引用imageobject

回答

0
public UnityEngine.UI.Image imageobject = new UnityEngine.UI.Image(); 

你只是定義實例,而不是從類中創建。

+0

通過這樣做,錯誤CS0122:'UnityEngine.UI.Image.Image()'由於其保護級別而無法訪問。這個錯誤發生了 –

1

您必須初始化函數中的myFruit變量。

在函數中做Sprite myFruit = Resources.Load("watermalon", typeof(Sprite)) as Sprite;

Sprite myFruit; 

void Start() 
{ 
    myFruit = Resources.Load("watermalon", typeof(Sprite)) as Sprite; 
} 

如果你不這樣做,你會得到這樣的錯誤:

Load is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour

編輯

另一個問題是,沒有從編輯器分配給imageobject變量。

由於imageobject是一個公共變量,因此將任何帶有Image組件的GameObject拖動到公共圖像對象插槽。您可以看到如何從this答案中的圖像中將對象拖動到可變插槽中。

+0

myFruit工作正常,它有圖像的實例,問題是與imageobject它沒有被設置爲實例和裁判爲空。 –

+0

不,'myFruit'不能正常工作。修復我的答案的第一部分,然後檢查編輯它回答你的第二個問題。你不只有一個問題。 – Programmer

+0

是的,我有這個錯誤負載不允許被調用,接下來要做什麼? –