Reputation: 382
somehow I can't deal with the simple scenario for the whole day :/
slotTypes = new InventoryItem[] { _Player.EqiupAmulet, _Player.EqiupArmor, _Player.EqiupBelt, _Player.EqiupBoots, _Player.EqiupCloak, _Player.EqiupArmor, _Player.EqiupGauntlets, _Player.EqiupHelmet };
Here want to store references to the InventoryItem public class; So, like, everytime I do something like:
InventoryItem _inv = new InventoryItem();
_Player.EqiuipArmor = _inv;
The slotTypes[1] and slotTypes[5] should hold reference to the _inv item now, but they do not, they stays null; I feel that I am missing something logical here, but hours of googling did not help me.
I've managed to pass the reference in functions using 'ref', but that did not solve the original problem.
_Player.EqiupArmor is defined as
public InventoryItem EqiupArmor
inside Player class;
Upvotes: 0
Views: 58
Reputation: 152654
The problem is your array is storing references to the objects. When you assign _Player.EqiuipArmor
to a new object, it points to a different instance but the reference stored in the array does not change.
You could create a class that takes a Player
class and exposes the various properties as an array:
public class InvertorySlots
{
private Player _Player;
public InventorySlots(Player player)
{
}
public InventoryItem[] GetItems()
{
return new InventoryItem[] {
_Player.EqiupAmulet,
_Player.EqiupArmor,
_Player.EqiupBelt,
_Player.EqiupBoots,
_Player.EqiupCloak,
_Player.EqiupArmor,
_Player.EqiupGauntlets,
_Player.EqiupHelmet };
}
}
Upvotes: 2
Reputation: 56726
Array actually hold the references to the objects. So look what happens in your scenario:
_Player.EqiuipArmor
is a null referenceslotTypes[0]
copies this and becomes another null reference_inv
references object X_Player.EqiuipArmor
reference is changed to the object XNow _Player.EqiuipArmor
is referencing X, while slotTypes[0]
is still a null reference.
Upvotes: 1
Reputation: 62012
If you have two distinct references to the same object instance, and you change one of those references to "point" to another instance, that does not imply that the other reference is changed. The other reference still refer the original instance.
Compare this:
object a = new object();
object b = a; // a and b are references to the same object
a = "something else";
// now a and b refer different objects; b still refers the original object
Upvotes: 3