I'm building a simple video game and I'm trying to find the best way to remove objects from and array that is the player inventory.
I want to use an ID for each game item but I'm not sure how to generate those IDs.
Obviously it wouldn't be productive to manually give every instance a unique Id.
I was thinking I could add a property on the constructor functions prototype or just directly on the constructor itself, called generated that increases by 1 with each instance created from it and then have each instance reach back up and use that as its ID.
Alternatively I could just randomly generate a random number for each object on its creation, however even with a large number their is very very small risk that you could have multiple objects with the same ID.
How I can add a unique ID to every object instance?
function Item(name,weight,value,description,type){
this.name=name;
this.weight = weight;
this.value=value;
this.description=description;
this.type=type;
this.id= this.generated;/*"this" here obviously means the a property immediately on the object its self on not something further up the chain*/
this.generated+=1;
}
Item.prototype.generated=0;
function Item(name,weight,value,description,type){
this.name=name;
this.weight = weight;
this.value=value;
this.description=description;
this.type=type;
this.id= this.__proto__.constructor.generated;/* this doesnt work either I'm assuming maybe because the constructor and __proto__ properties are added after everything in the constructor function runs, so its undefined?*/
this.__proto__.constructor.generated+=1;
}
Item.generated=0;