2017-04-21 164 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

是的,我有这个错误负载不允许被调用,接下来要做什么? –