- Home /
The question is answered, right answer was accepted
reference to different classes : item held by different type of owner
Hello everyone,
It's probably answered somewhere else but i couldn't formulate my question so that a search could find the answer.
Here's the thing : i'm ocding a simple 2D game seen from above. I'm imlplementing different types of items such as materials, tools, and the objects the character can use, called "Inventory" in my code. Such inventory can be either held by a character or lying on the ground, so both the classes "Tile" and "Character" have a "Inventory" reference. But the inventory needs to know who owns it. And i don't know how to do it elegantly.
what i did before was to have simply 2 references, one of type "Character" and one of type "Tile", but since other type of owner will add in the future this add more and more lines of code, and the checks will be quite painful to implement...
DO you know a way of solve this riddle? Thanks in advance, Gabriel
Hey Gabriel, will the inventory script initialize as a component of a gameObject or as a component of a different 'Inventory' gameObject?
the way i did, inventory is not linked at all to a gameobject, it's just a script. The gameobject have a script called "InventoryController" that interprets the "Inventory" scritp attached to it to render it. This way when i save i store only the values of the model.
So what you can do is get the gameObject of the inventoryController script by just using something like private GameObject owner = gameObject
And then use that owner reference from your inventoryController script inside of your Inventory script.
Answer by bl4cksky · Jul 27, 2018 at 07:15 PM
I'll look at it. And could an interface do the work?
I used intefaces very little, but i could implement a "CanStockInventory" interface and have "Character" and "Tile" have it? And the inventory reference would be in the interface?
Okay i solved it from another way. I implementaed an InventorySlot class that has all the ownership reference, except that it shouldn't change since it's attached to whatever tile or character that can have an inventory, so the functions to change ownership of inventory just applies to the slot the inventory is attached to. This way the code is simpler and i can freely move inventories all around.
Thanks for the answers Carterryan1990 and BDCakerules
Answer by Carterryan1990 · Jul 27, 2018 at 06:30 PM
You should look up script-able objects. I think that may help solve your issue. If your destroying the object a script-able object being destroyed wont remove any of the properties or inventory items.
Follow this Question
Related Questions
Referencing all objects in scene 2 Answers
trouble with referencing a componenet (bool) 1 Answer
Instantiated Objects dont get their Script referenced properly 2 Answers
why doesn't my reference work? 1 Answer
Using a Scriptable Object as a Config 0 Answers