关于 Unity 升级到 2018.3 以上命名空间不存在解决方案

错误发生的原因:

例如: 关于 Unity 升级到 2018.3 报 The type or namespace name ‘Remoting’… 错误

今天得到好消息是 Unity2018.3 将支持 C#7,于是兴奋地升级了下。
结果报了个 The type or namespace name ‘Remoting’ does not exist in the namespace ‘System.Runtime’这样的错误。
网上查了下这是因为 API LEVEL 这边默认的是 2.0 的原因,升级到 4.X 就解决了。

解决办法:
File -> build setting -> play setting

NO_FRAME 错误

如果勾选了 Autoconnect Profiler 选项,并且在开着 editor 的情况下使用 UPR App 或者 UPR Desktop ,可能出现 NO_FRAME 的情况。
请关闭 Editor Profiler 窗口,或者在不勾选 Autoconnect Profiler 选项时重新 Build And Run,并重新使用 UPR 进行测试。
– UPR 开发小组 敬上

unity 打包 android 卡在 Building Gradle project

unity2020.1.0f1c1 打包 android 的时候,卡在 Building Gradle project

可能是在下载 gradle,国内网络下载可能很慢或失败,所以一直卡在这里

自己下了个 gradle,比如:https://services.gradle.org/distributions/gradle-5.4.1-all.zip
然后在 unity 中配置 gradle 路径

Unity 报错:‘** Class‘ is missing the class attribute ‘ExtensionOfNativeClass‘!

这个问题呢,虽然不会影响程序的运行,但是报一个红杠杠也很不舒服,
程序员的天职是啥?不就是无限的解决 bug 嘛
让我们分析一个这个问题

1
** Class’ is missing the class attribute 'ExtensionOfNativeClass

翻译:** Class’缺少类属性’ExtensionOfNativeClass

这个就是当我们继承了 mono, 才会有这些属性,然而没有继承 mono, 却被挂到了场景中,直接把脚本在场景中挂载中移除掉就可以了, 就会报一个这样的错误,网上很多说什么重名的,新建文件夹没有关系,这个只是没有继承 mono 就被挂到对象上了去了确实属性才会报这个错误

导出游戏时需要选择空的文件夹

否则会出现以下错误:
导出错误

CS0103 错误:使用的变量名或者方法名并不存在于当前上下文中

** 错误:** error CS0103: The name ‘gameobject’ does not exist in the current context
** 解决:** 脚本中获取游戏对象使用 gameObject。
gameObject
注:Debug.Log(“”); 表示调试时输出引号中的内容。

CS1061 错误: 尝试调用方法或访问不存在的类成员

** 错误:** error CS1061: ‘Vector2’ does not contain a definition for ‘X’ and no accessible extension method ‘X’ accepting a first argument of type ‘Vector2’ could be found (are you missing a using directive or an assembly reference?)
** 解决:** 脚本中获取游戏对象的位置使用 x、y、z。
xy
①请确保正确输入了成员名。
②如果有权修改此类,则可以添加缺少的成员并实现它。
③如果没有修改此类的权限,则可以添加扩展方法。

Unity 怎么点都没反应:可能是进入了死循环

** 问题:** Unity 怎么点击都没反应,但又不是卡住了,考虑可能是代码写的不当,出现了死循环代码。
** 解决:** 先用任务管理器将 Unity 关闭,再仔细检查代码,确定逻辑无误后再调试运行。

CS0428 错误: 类型转换错误

检查代码或者使用强制转换。

CS1656 错误: 无效赋值错误

检查代码的赋值是否正确。

NullReferenceException:空指针错误,Object 并没有作为一个对象的实例

** 错误 **:NullReferenceException: Object reference not set to an instance of an object
** 解决 **:对象需要实例化后才能使用。
深刻的教训:有次为了图方便,对象名是复制的,多复制了一个空格,导致一直报没有实例化的错误,找了两天才找到。இ௰இ

UnassignedReferenceException: 变量未被赋值错误

** 错误 **:UnassignedReferenceException: The variable XXXX of XXXXX has not been assigned.
** 解决 **:脚本中写明该变量为 public,而在 Inspector 窗口中却未给其赋值,在 Inspector 窗口赋值即可。

场景不能加载问题

** 错误 **:Scene ‘WhacAMole’ couldn’t be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
To add a scene to the build settings use the menu File->Build Settings…
** 解决 **:选择 File->Build Settings->Add open scenes在这里插入图片描述

IndexOutOfRangeException: 数组下标越界问题

** 错误 **:IndexOutOfRangeException: Index was outside the bounds of the array.
** 解决 **:限制数组索引,使其不要越界。

ArgumentException: 要实例化的对象是空的

** 错误 **:ArgumentException: The Object you want to instantiate is null.
** 解决 **:在 Inspector 或 Scripts 中引用要实例化的对象。

ArgumentOutOfRangeException: 超出索引

** 错误 **:ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
** 解决 **:注意访问集合元素时,索引是否超出了范围。

CS0108 警告: 变量声明与基类有相同的名字

** 错误 **:warning CS0108: ‘MouseDrag.camera’ hides inherited member ‘Component.camera’. Use the new keyword if hiding was intended.
在这里插入图片描述
** 解决一 **:在变量声明处添加 new 关键字。
在这里插入图片描述
** 解决二 **:改变变量的名字避免产生混淆。
在这里插入图片描述

InvalidCastException: 强制转换异常

** 错误 **:InvalidCastException: Specified cast is not valid.
** 解决 **:Unity 中 AudioSource 使用 Resources.Load() 方法加载。

FormatException: 输入的字符串格式有误

** 错误 **:FormatException: Input string was not in a correct format.
** 解决 **:检查读取到的值的格式。

StackOverflowException: 请求的操作导致堆栈溢出

** 错误 **:StackOverflowException: The requested operation caused a stack overflow.
** 解决 **:检查程序中是否存在递归调用,导致程序卡死。

InvalidOperationException: 输入系统包设置问题

** 错误 **:InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
** 解决 **:点击菜单栏的 Edit->Project Settings…->Player->Other settings,将 active lnput handling 选项设置为 Both 即可。
在这里插入图片描述

在场景中有多个音频监听器

** 提示 **:There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.
** 解决 **:一般新创建一个场景后,在 Main Camera 中都有一个 Audio Listener 组件,用于监听场景中是否有音频的播放。如果需要场景中的音乐不随场景的切换而重置,需要场景中只有一个 Audio Listener,删除一个即可。

父物体设置不成功

** 错误 **:Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: ‘AudioCube’).

1
2
3
4
5
6
// 加载预制体 
GameObject audioCube = Resources.Load<GameObject>("AudioCube");
// 初始化预制体
GameObject gameObject = Instantiate(audioCube, new Vector3(1, 0, 0), Quaternion.identity);
// 设置父物体
audioCube.transform.SetParent(AudioCubes.transform);

预想将使用预制体 audioCube 实例化的物体的父物体设置为 AudioCubes,如上方法会导致设置不成功。
** 解决 **:
使用 Instantiate 的重载方法直接把物体的父物体设置好就不会有如上问题:

1
2
3
4
// 加载预制体 
GameObject audioCube = Resources.Load<GameObject>("AudioCube");
// 初始化预制体
GameObject gameObject = Instantiate(audioCube, new Vector3(1, 0, 0), Quaternion.identity,AudioCubes.transform);

Component GUI Layer in Main Camera for Scene Test.unity is no longer available:不再支持场景 Test.unity 中挂载在 Main Camera 上的组件 GUI Layer

** 错误 **:Component GUI Layer in Main Camera for Scene Test.unity is no longer available.
** 解决 **:将 Main Camera 上的 Flare Layer 组件移除即可。
在这里插入图片描述

The namespace ‘global namespace’ already contains a definition for ‘Test’:项目资源中存在和 Test 重复名称的脚本被调用

** 错误 **:The namespace ‘global namespace’ already contains a definition for ‘Test’.
** 解决 **:找到相同名字的脚本,修改其中一个即可。

PrecompiledAssemblyException: 在当前平台包含多个同名 Test.dll 的预编译程序集,每个平台只允许一个具有相同名称的程序集

** 错误 **:PrecompiledAssemblyException: Multiple precompiled assemblies with the same name Test.dll included or the current platform. Only one assembly with the same name is allowed per platform.
** 解决 **:找到重复的另一个 Test.dll,删除掉即可。

CS0656 错误: 缺少编译器要求的成员 “Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create”

** 错误 **:error CS0656:Missing compiler required member ‘Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create’.
** 原因 **:在 net core 使用动态类型 dynamic。
** 解决 **:

  1. 不用 dynamic 类型。
  2. 在使用的地方添加一个 dll,Microsoft.CSharp,或者用 NuGet 添加 Microsoft.CSharp 即可。
    在 Visual Studio 中打开 NuGet 包管理器,搜索 Microsoft.CSharp 后点击安装。
    在这里插入图片描述

无法正确读取资源的 GUID

** 错误 **:Could not extract GUID in text file XXX at line XXX.
** 解决 **:重置项目资源的 GUID

  1. 菜单栏 ->Edit->ProjectSettings-> 左侧 Editor 菜单栏,右侧找到 Asset Serialization,将其 Mode 设置为 Force Text:
    在这里插入图片描述
  2. 在 Project 面板的 Assets 目录下新建一个名为 Editor 的目录,在其中新建一个 UnityGuidRegeneratorMenu 脚本,写入如下代码,注意其中的路径需要修改成自己需要重置 GUID 的文件夹目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;

namespace UnityGuidRegenerator {
public class UnityGuidRegeneratorMenu {
[MenuItem("Tools/Regenerate asset GUIDs")]
public static void RegenerateGuids() {
if (EditorUtility.DisplayDialog("GUIDs regeneration",
"You are going to start the process of GUID regeneration. This may have unexpected results. \n\n MAKE A PROJECT BACKUP BEFORE PROCEEDING!",
"Regenerate GUIDs", "Cancel")) {
try {
AssetDatabase.StartAssetEditing();

string path = Path.GetFullPath(".") + Path.DirectorySeparatorChar + "Assets/_Game";// 要更新 guid 的文件夹
UnityGuidRegenerator regenerator = new UnityGuidRegenerator(path);
regenerator.RegenerateGuids();
}
finally {
AssetDatabase.StopAssetEditing();
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
}
}
}
}

internal class UnityGuidRegenerator {
private static readonly string[] kDefaultFileExtensions = {
// "*.meta",
// "*.mat",
// "*.anim",
// "*.prefab",
// "*.unity",
// "*.asset"
"*.*"
};

private readonly string _assetsPath;

public UnityGuidRegenerator(string assetsPath) {
_assetsPath = assetsPath;
}

public void RegenerateGuids(string[] regeneratedExtensions = null) {
if (regeneratedExtensions == null) {
regeneratedExtensions = kDefaultFileExtensions;
}

// Get list of working files
List<string> filesPaths = new List<string>();
foreach (string extension in regeneratedExtensions) {
filesPaths.AddRange(
Directory.GetFiles(_assetsPath, extension, SearchOption.AllDirectories)
);
}

// Create dictionary to hold old-to-new GUID map
Dictionary<string, string> guidOldToNewMap = new Dictionary<string, string>();
Dictionary<string, List<string>> guidsInFileMap = new Dictionary<string, List<string>>();

// We must only replace GUIDs for Resources present in Assets.
// Otherwise built-in resources (shader, meshes etc) get overwritten.
HashSet<string> ownGuids = new HashSet<string>();

// Traverse all files, remember which GUIDs are in which files and generate new GUIDs
int counter = 0;
foreach (string filePath in filesPaths) {
EditorUtility.DisplayProgressBar("Scanning Assets folder", MakeRelativePath(_assetsPath, filePath), counter / (float) filesPaths.Count);
string contents = File.ReadAllText(filePath);

IEnumerable<string> guids = GetGuids(contents);
bool isFirstGuid = true;
foreach (string oldGuid in guids) {
// First GUID in .meta file is always the GUID of the asset itself
if (isFirstGuid && Path.GetExtension(filePath) == ".meta") {
ownGuids.Add(oldGuid);
isFirstGuid = false;
}
// Generate and save new GUID if we haven't added it before
if (!guidOldToNewMap.ContainsKey(oldGuid)) {
string newGuid = Guid.NewGuid().ToString("N");
guidOldToNewMap.Add(oldGuid, newGuid);
}

if (!guidsInFileMap.ContainsKey(filePath))
guidsInFileMap[filePath] = new List<string>();

if (!guidsInFileMap[filePath].Contains(oldGuid)) {
guidsInFileMap[filePath].Add(oldGuid);
}
}

counter++;
}

// Traverse the files again and replace the old GUIDs
counter = -1;
int guidsInFileMapKeysCount = guidsInFileMap.Keys.Count;
foreach (string filePath in guidsInFileMap.Keys) {
EditorUtility.DisplayProgressBar("Regenerating GUIDs", MakeRelativePath(_assetsPath, filePath), counter / (float) guidsInFileMapKeysCount);
counter++;

string contents = File.ReadAllText(filePath);
foreach (string oldGuid in guidsInFileMap[filePath]) {
if (!ownGuids.Contains(oldGuid))
continue;

string newGuid = guidOldToNewMap[oldGuid];
if (string.IsNullOrEmpty(newGuid))
throw new NullReferenceException("newGuid == null");

contents = contents.Replace("guid: " + oldGuid, "guid: " + newGuid);
}
File.WriteAllText(filePath, contents);
}

EditorUtility.ClearProgressBar();
}

private static IEnumerable<string> GetGuids(string text) {
const string guidStart = "guid: ";
const int guidLength = 32;
int textLength = text.Length;
int guidStartLength = guidStart.Length;
List<string> guids = new List<string>();

int index = 0;
while (index + guidStartLength + guidLength < textLength) {
index = text.IndexOf(guidStart, index, StringComparison.Ordinal);
if (index == -1)
break;

index += guidStartLength;
string guid = text.Substring(index, guidLength);
index += guidLength;

if (IsGuid(guid)) {
guids.Add(guid);
}
}

return guids;
}

private static bool IsGuid(string text) {
for (int i = 0; i < text.Length; i++) {
char c = text[i];
if (
!((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z'))
)
return false;
}

return true;
}

private static string MakeRelativePath(string fromPath, string toPath) {
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);

Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());

return relativePath;
}
}
}

  1. 这时,返回 Unity,等待编译一段时间后,可以发现菜单栏多出了一个 Tool 菜单,选中下面的 Regenerate asset GUIDs,就可以对选定文件夹下资源的 GUID 进行重置了。

Visual Scripting 版本不兼容问题

** 警告 **:Inspectors are disabled when plugin versions mismatch to prevent data corruption
在这里插入图片描述
在这里插入图片描述

** 解决 **:Edit > Project Settings,左侧栏找到 Visual Scripting,点击 Generate 按钮,如下图所示:
在这里插入图片描述
等待 Unity 编译完成即可。

Package Manager:A warning occurred: You do not have entitlements for this package.

在这里插入图片描述
该问题是已知 bug 并存在于一些版本之中,可以提交 bug report 让官方来修复该版本的问题。
** 其他解决方案 **:

  1. 重启 Unity Editor(一般就可以解决)
  2. 右键点击 Assets 文件夹并选择 reimport all
  3. 删除该项目文件夹下的 Library 文件夹后重新打开该项目
  4. 升级 Unity Editor 版本

编辑器布局无法完全加载问题

** 提示 **:The editor layout could not be fully loaded, this can happen when the layout contains EditorWindows not available in this project
UnityEditor.WindowLayout:LoadDefaultWindowPreferences()
** 解决 **:建立的项目名称是中文名,改成英文即可。

hierarchy 栏目中的 gameobject 不能拖动到 prefab 上的脚本中

** 问题 **:当把 prefab 从当前 scene 中删除之后,再添加到另外一个 scene 中时,unity 无法找到在第一个 scene 中添加的 gameobject。
** 解决 **:把该 gameobject 也制成 prefab,即可以让该 gameobject 成为 prefab 的孩子。


没有显示在 Console 中的编译错误可能问题

  • 函数引用没加 ()
  • 用到了包,但是没有用 using 引用

to be continued…