简体   繁体   English

Unity / C#,创建对现有类实例(GC)的引用

[英]Unity/C#, Creating references to existing class instances (GC)

So I'm making a small mobile game and trying to structure everything best as I can... but there be questions. 因此,我正在制作一款小型手机游戏,并尽我所能尽力构建所有内容……但是仍然存在疑问。

Assume you have a collection of weapons in an array, how bad would it be to create a reference (activeWeapon) to a weapon in the collection and use that rather than accessing the collection directly in the array? 假设您在一个数组中有一个武器集合,那么创建一个对集合中武器的引用(activeWeapon)并使用它而不是直接在数组中访问该集合有多糟糕?

Eg 例如

public Weapon activeWeapon; // Accessing this, and re-assigning from collection when changing weapon.
public Weapon[] weaponCollection;

I'm assuming "activeWeapon" is just an address pointer right? 我假设“ activeWeapon”只是一个地址指针,对不对? So assigning it to another weapon in the collection should not give too much garbage? 因此,将其分配给集合中的另一种武器应该不会产生太多垃圾?

Or am I being a bad man? 还是我是个坏人?

If your you defined a Weapon as a Class in C# (ie not a Struct) it is completely OK to do it the way you described. 如果您在C#中将Weapon定义为类(即不是Struct),则完全可以按照您描述的方式进行操作。 activeWeapon is just a reference, so you can change it as many times as you want and it will not cause any additional garbage as you will still have a single instance of that Weapon even if you reference it twice from two different places. activeWeapon只是一个参考,因此您可以根据需要进行多次更改,并且不会造成任何额外的垃圾,因为即使您在两个不同的位置两次引用了该Weapon也仍然只有一个Weapon实例。

You can read more about reference types here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types 您可以在此处阅读有关参考类型的更多信息: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/reference-types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM