I want to add an item to the inventory with using the name of the picked entity.
I call the function addItem with this name and want to use this to select the right attribute.
In the example below the picked entity is a stone with the name “Stone”.
Instead of using the attribute this.Stone I like use this.item where item is Stone.
With this way I get the error ‘Cannot read property ‘resource’ of undefined’.
Any idea how to make this possible?
var Inventory = pc.createScript('inventory');
Inventory.attributes.add('Stone', {type: 'asset', assetType: 'texture'});
// initialize code called once per entity
Inventory.prototype.initialize = function() {
// This "Stone" will be the name of the picked entity
this.addItem("Stone");
};
Inventory.prototype.addItem = function(item) {
// Find an empty slot
var slots = this.entity.findByTag("Slot");
for (var slot = 0; slot < slots.length-1; slot++) {
if (slots[slot].element.texture.name === "Empty") {
// Add the item to the empty slot of the inventory
console.log(slots[slot].name + " is Empty");
slots[slot].element.texture = this.item.resource;
break;
}
}
};
Ah, I see. You can consider attributes as keys of an object, as such, you should be able to access them by their names:
var name = 'Stone';
console.log( this[name] );
Edit:
var Inventory = pc.createScript('inventory');
Inventory.attributes.add('Stone', {type: 'asset', assetType: 'texture'});
// initialize code called once per entity
Inventory.prototype.initialize = function() {
// This "Stone" will be the name of the picked entity
this.addItem("Stone");
};
Inventory.prototype.addItem = function(name) {
// Find an empty slot
var slots = this.entity.findByTag("Slot");
for (var slot = 0; slot < slots.length-1; slot++) {
if (slots[slot].element.texture.name === "Empty") {
// Add the item to the empty slot of the inventory
console.log(slots[slot].name + " is Empty");
slots[slot].element.texture = this[name].resource;
break;
}
}
};