简体   繁体   中英

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?

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? 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. 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.

You can read more about reference types here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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