So I am trying to fix a problem, right now this script here creates a chest and then sets the item script in its variables. But for some reason the “Name” variable on the item keeps getting set to “”. I dont understand why because I try to disconect it by makeing the variable equal null but when I make the items name on the character equal to “” it also makes the item equal to “”. Please help. Thanks!
if(CharacterScriptA.ThisCharacter.Inventory[0].Name != "" ){
if(GUILayout.Button (CharacterScriptA.ThisCharacter.Inventory[0].Name + "|" + CharacterScriptA.ThisCharacter.Inventory[0].Stat + " " + CharacterScriptA.ThisCharacter.Inventory[0].PlusMinus + " " + CharacterScriptA.ThisCharacter.Inventory[0].Value)) {
var chestInstant = Network.Instantiate(Chest, Target.position, Target.rotation, 0);//create chest
var Item: ItemScript = chestInstant.GetComponent(ItemScript);
Item.ThisItem = CharacterScriptA.ThisCharacter.Inventory[0];//set the chest's contents to the inventory you selected
Item = null;
CharacterScriptA.ThisCharacter.Inventory[0].Name = "";
}
}
I’m not big on JavaScript. I use C# but you seems to be assigning your inventory item to your chest by reference. In other words - CharacterScriptA.ThisCharacter.Inventory[0] is an object. When you assign it to Item.ThisItem you are not making a copy of the inventory object, you are assigning a reference. So when you assign “” to Name property of CharacterScriptA.ThisCharacter.Inventory[0] object it reflects in your chest object by reference.
Hmm you may be right. CharacterScriptA is the script on my character with the variables on it by the way. Im still a bit stumped but thanks! Any ideas even in C on how I could not make them referanced after I use them?
The only way I know is to create a copy constructor which would accept an old object as a parameter and copy all the variables from it into the one being constructed. Again, not sure how to implement that in JavaScript. Generally the idea is not to assign an existing object but create a new one, copy all the relevant properties of the old one into a new one and then assign a new one. As a result, you can do anything with the old object and it will not reflect on a new one. Again, sorry if I’m barking up the wrong tree here. Hope it helps.
var curItem = CharacterScriptA.ThisCharacter.Inventory[0];
Item.ThisItem = curItem;//set the chest's contents to the inventory you selected
curItem = null;
I don’t think you are making a copy still. Your lines 1 and 2 are still assigning by reference. Unless JavaScript does a deep copy during the object assignment (doubt it). The only safe assignments by value are those of the simple types (numbers, characters, NOT objects). Again, all of this based on my C# knowledge. I do believe JavaScript behaves the same way though.