c# - 为什么我不能在 Unity 中引用对象?

标签 c# unity3d

我想创建一个 Vector3 类型的对象来引用我的玩家位置,以便我可以在我的脚本中使用一个较短的名称。但我没有这样做。看起来新对象指向其他地址。

我写了一些这样的代码:

//PlayerController.cs
vector3 playerPos = transform.position;
Debug.Log(System.Object.ReferenceEquals(playerPos,transform.position)); 

输出是

false

这是什么原因造成的?我如何才能正确引用玩家的位置?

最佳答案

What caused this

下面是一个简单的解释。

transform.positionVector3 .

Vector3struct .

Struct 是一种值类型。

在 Unity 的文档中查看 Unity API 的类型总是很好的。这在 Unity 中工作时非常重要。

enter image description here

当你这样做时:

vector3 playerPos = transform.position;

创建新的 struct 并将 transform.position; 中的值复制到 playerPos 变量。由于变量是值类型并被复制,对其执行 System.Object.ReferenceEquals 应该返回 false


I want to create a vector3-type object referring to my player's position so that I can use a shorter

在这种情况下,您必须更改 Vector3Transform .

Transform myPos = null;
void Start()
{
    myPos = transform;
}

然后你可以这样做:

myPos.position = newPos; 

必须将位置声明为 Transform 的原因而不是 Vector3是因为Transform是一个类,一个类存储对象的引用。

类是引用类型。

enter image description here

Debug.Log(System.Object.ReferenceEquals(myPos, transform)); 应该返回 true 因为 myPostransform 都是类,myPos 变量引用 transform 变量。

因此,无论何时您使用 myPos.position; 访问您的位置,它都会为您提供游戏对象的最新位置,这也是 (transform.position) 自myPos 变量是一个 class,它引用了 transform,这也是一个 class

假设 myPosstruct 或声明为 vector3 myPos 而不是 Transform myPos,那么 myPos 变量在分配时将保存 transform.position 的副本值,并且永远不会返回游戏对象的最新位置,因为它是一个副本。

您可以了解更多关于 class vs struct 的信息在这里。

最后 System.Object.ReferenceEquals 说的是“ReferenceEquals”而不是“ValueEquals”,所以这甚至是不言自明的。您可以在 class/referece 类型上使用它,而不是在 structs 或值类型上使用它。

关于c# - 为什么我不能在 Unity 中引用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599835/

相关文章:

c# - 如何在 sql server 中存储 SecureString?

c# - 如何在 C# 中解压 .bz2 文件?

c# - 全变色算法

android - 如何使用 Unity 在 Android 设备上的每个纵横比上显示游戏的相同部分?

unity3d - 为什么 Unity 在构建中包含编辑器目录

c# - 如何找到 VLC 属性库 (C# Unity)

c# - 了解以下异步等待调用之间的区别

c# - 面向 .NET Core 2.0

c# - 为什么要使用隐式/显式运算符?

unity3d - 使用 WebGL Unity 连接到 TCP 服务器