版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
前言
我在学习Unity绘制静态贴图时,使用到了Load和LoadAll两个函数,这两个函数的作用是加载Resources的文件资源。但我在使用LoadAll的时候碰到了一点问题。
代码展示
using UnityEngine;
using System.Collections;
public class picture_script : MonoBehaviour {
private Texture2D texSingle;
private Object[] texAll;
void OnGUI() {
//绘制一个贴图
if (GUI.Button (new Rect (0, 10, 100, 50), "加载一张贴图")) {
if(texSingle == null){
texSingle = (Texture2D)Resources.Load("texture/0");
}
}
//绘制一组贴图
if (GUI.Button (new Rect (0, 130, 100, 50), "加载一组贴图")) {
if(texAll == null) {
texAll = Resources.LoadAll("Texture");
}
}
if (texSingle != null) {
GUI.DrawTexture(new Rect(110,10,120,120),texSingle,ScaleMode.StretchToFill,true,0);
}
if(texAll != null){
for(int i=0; i<texAll.Length; i++){
GUI.DrawTexture(new Rect(110+i*120,130,120,120),(Texture2D)texAll[i],ScaleMode.StretchToFill,true,0);
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
运行效果
当绘制一张贴图的时候,程序时能够正常运行的:
但是当绘制一组图片的时候,程序就出问题了:具体是只加载出了一张图片,并且Console处还一直报错
报的错误为
InvalidCastException: Cannot cast from source type to destination type.
picture_script.OnGUI () (at Assets/Script/picture_script.cs:29)
大意是说29行我的原类型无法成功转换成目标类型,但是第一张图片却能够成功转换。
解决错误
首先我怀疑是我图片没有全部加载,所以先打印了一下我的数组长度:
if (GUI.Button (new Rect (0, 130, 100, 50), "加载一组贴图")) {
if(texAll == null) {
texAll = Resources.LoadAll("Texture");
}
Debug.Log(texAll.Length);
}
令我感到奇怪的是,我的resources下的texture文件夹下总共也就5张图片,然而我却加载了10张图片
没有办法只能插入断点调试了,我这里用的是monoDevlop来进行断点调试
1)首先,现在18行插入断点
2)然后在monoDev中选择run->Attach to Process
3)最后选择Unity Editor就可以进入调试界面了
4)在Unity界面中点击运行,然后点击加载一组图片的按钮,monoDev中就会变成这样。
5)在左下角watch这一栏中的Name处添加我们想要查看的变量,这里我选择查看我的数组
6)然后选择step over
7)这时我就发现了产生错误的原因,是因为他在加载资源的时候,不仅加载了Texture2D的格式,还加载了Sprite的格式,而Sprite无法转换成Texture2D的格式
解决问题
修改我的代码:
using UnityEngine;
using System.Collections;
public class picture_script : MonoBehaviour {
private Texture2D texSingle;
private Object[] texAll;
void OnGUI() {
if (GUI.Button (new Rect (0, 10, 100, 50), "加载一张贴图")) {
if(texSingle == null){
texSingle = (Texture2D)Resources.Load("texture/0");
}
}
if (GUI.Button (new Rect (0, 130, 100, 50), "加载一组贴图")) {
if(texAll == null) {
texAll = Resources.LoadAll("Texture");
}
Debug.Log(texAll.Length);
}
if (texSingle != null) {
GUI.DrawTexture(new Rect(110,10,120,120),texSingle,ScaleMode.StretchToFill,true,0);
}
if(texAll != null){
for(int i=0; i<texAll.Length; i++){
if(i % 2 == 0){
GUI.DrawTexture(new Rect(110+i*120/2,130,120,120),(Texture2D)texAll[i],ScaleMode.StretchToFill,true,0);
}
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
新的运行效果:
加载单个图片:
加载一组图片:
总结
由于我是照着电子书学习的,这段代码也是书上给的,我也完全照着书上打,所以也不知道产生问题的原因,等过几天有空了再从网上查阅一下资料好了。