最新文章
泰课新年学课蛇来运转欢度春节活动
02-01 20:25
共庆2024圣诞、元旦泰课双蛋活动
12-16 10:21
泰课共庆75周年国庆活动!
10-05 21:24
暑假双月联动学习计划 7月15 - 8月21日
07-14 23:09
泰课在线劳动光荣,勤学快乐之五月勤学季活动
04-30 21:19
2024年青春绽放开学季活动
03-11 13:01
unity5.x-2019导入老项目包含GUI对象的处理方式
新同学在打开或导入一些老项目时,可能常常会遇到包含过去 GUI 对象而出现报错的情况。下面我们将详细介绍不同 Unity 版本下的处理方式,并给出具体示例代码。
示例报错代码
以下是一个包含旧 GUI 对象的示例代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
// Use this for initialization
public static GameManager _instance;
public int score = 0;
private GUIText uiText;
void Awake() {
_instance = this;
uiText = GameObject.FindGameObjectWithTag("scoreGUI").guiText;
}
// Update is called once per frame
void Update() {
uiText.text = "Score:" + score;
}
}
在较新的 Unity 版本中,这段代码会因为使用了旧的 GUIText 而报错。
Unity 2019 版本处理方式
在 Unity 2019 版本中,UI 是通过 Package Manager 添加的。如果你的项目 Package 中没有 Unity UI,需要到 Package Manager 中进行添加。
修改代码
对于上述示例代码,需要进行如下修改:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
// Use this for initialization
public static GameManager _instance;
public int score = 0;
private Text uiText;
void Awake() {
_instance = this;
uiText = GameObject.Find("scoreGUI").GetComponent<Text>();
}
// Update is called once per frame
void Update() {
uiText.text = "Score:" + score;
}
}
主要修改点如下:
- 引入
UnityEngine.UI命名空间,因为新的 UI 系统使用该命名空间。 - 将
GUIText类型替换为Text类型。 - 使用
GetComponent<Text>()方法获取Text组件,而不是直接访问guiText。
Unity 5.x - 2018 版本处理方式
在 Unity 5.x - 2018 版本中,修改代码的方式与 Unity 2019 类似,同样需要将旧的 GUIText 替换为新的 Text 类型。
另外,如果你的项目属性中没有包含对 UI 的引用,可以自己修改项目属性文件(一个 .csproj 文件)来添加对 UI 的引用。你可以在 Visual Studio 菜单的【项目】中找到并编辑该项目属性文件。
通过以上步骤,你就可以成功处理在不同 Unity 版本中导入包含旧 GUI 对象的老项目时出现的问题。