user2426290
user2426290

Reputation: 382

pass class reference in array

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

Answers (3)

D Stanley
D Stanley

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

Andrei
Andrei

Reputation: 56726

Array actually hold the references to the objects. So look what happens in your scenario:

  1. _Player.EqiuipArmor is a null reference
  2. slotTypes[0] copies this and becomes another null reference
  3. _inv references object X
  4. _Player.EqiuipArmor reference is changed to the object X

Now _Player.EqiuipArmor is referencing X, while slotTypes[0] is still a null reference.

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

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

Related Questions