Mysterious Problem with builtin arrays custom Class.

Hi. I will try shortly explain my problem.
I have 3 scripts: Database.js ; Player.js; Barter.js.

Database.js:

static var items : Item[];

class Item{
	var id :int;
	var name : String;
	var price : int;
	var trade : boolean=false;
        // --more variables--
}

Barter.js:

var items : Item[];
// + more code which is not important

Here starts the mystery :smile: Player.js:

static var inventory : Item[] = new Item[516];
var shop : Barter;

Function OnGUI(){

	inventory[0].trade=false;
	 if (inventory[0].trade) print("Lag"); // Here is every thing ok because never this shows up in console;
	if (shop) shop.items[0].trade=true;
[COLOR="red"]	 if (inventory[0].trade) print("????");// But this shows always !!! So it means that changing barter.items changes player.inventory ? [/COLOR]
}

Any Ideas what is wrong? :face_with_spiral_eyes:

Try making the variables non-static, since static means only one instance can exist in the class.

–Eric

You see Player.js and Database.js are only one instance in scene. But for barter.js the items[ ] is not public. I realy dont want to change Player.js inventory to public because a lot of code i need to change to do it. But thanks! Any other suggestions?

I agree with Eric. Static variables IMO are quite dangerous unless you know what you are doing. And i noticed this

if (shop) shop.items[0].trade=true; // Original script

if (shop) shop.items[0].trade = true; // Does this even make any sense?

if (shop) shop.items[0].trade == true; // Is this what you want then? Then what is (shop) for?

if ((shop) shop.items[0].trade); // Removed the == since this also checks if it is true and (shop) means casting?

Anyways your codes are confusing. But hope what i said do help you.

if(shop) check if shop is not null. i.e. if(shop != null) so it makes sense.
It is indeed strange, this behaviour. You should be able to have static and non static arrays of variables of the same class. Try to simplify the test case as much as you can. Also try restarting unity. Maybe try renaming the second items so that is not the same as the static one, although that shouldn’t matter.

Tanks for suggestions. I will try to change Player.inventory as public variable. But anyway i think that problem is somewhere else.

This is only part of code. Actually Player.js is about 400 lines long so it make sense. :wink:

Oh yes, i found where is problem. Eric was right :slight_smile: problem is with static variables. It is with Database.js static var items[ ] because when i write Player.inventory[0].trade=true I actually change Database.js items[×]. And that’s because in AddItem()function i wrote Player.inventory[×]=Database.items[y]; Dohh! How i understand Player.inventory works like shortcut to Database.items and don’t storage data like normal. Thanks for help! Cheers!!! :))

P.S. I found easy solution for this without rewriting database.items as non-static :slight_smile: