# loot system with Scriptable Objects

**URL:** https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502
**Category:** Scripting
**Tags:** Scripting, Question
**Created:** [June 13, 2023, 1:15pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502 "2023-06-13T13:15:28Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![ooffeekkii](https://avatars.discourse-cdn.com/v4/letter/o/82dd89/32.png) [@ooffeekkii](https://discussions.unity.com/u/ooffeekkii)
#### Post date: [June 13, 2023, 1:15pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/1 "2023-06-13T13:15:28Z")

</div>

Hello,  
I am a unity begginer working on my first project.  
I have made some items assets using scriptable objects.

each item has the attributes: name, decription, id, price, Image.

I have two problems:

1. I want to make an area in the store that the player can buy one item that is randomly taken out of all the items. that is why I need a script that can get access to any item(scriptable object), the solution of dragging all the items into one script input should be possible but I don’t feel like it would be correct. (should be arround 20 items and I might remove/add some later)

2. I want that each item will have a function that it will do. is it possible/recommended to have another attribute that is a function (i come from python which is very easy to do)  
in a way that the attributes of the items will be: name, decription, id, price, Image, **\<functionality(game\_state)\>**.

I appreciate any help and general tips,  
Thank you for reading!

---

<div class="post-metadata">

### Author: ![Kurt-Dekker](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/kurt-dekker/32/101578_2.png) [@Kurt-Dekker](https://discussions.unity.com/u/Kurt-Dekker)
#### Post date: [June 13, 2023, 2:14pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/2 "2023-06-13T14:14:22Z")

</div>

Sounds great! Get to work. A loot system is a MASSIVE undertaking and every minute you delay is wasted time.

Keep this in mind:

**These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.**

Inventory code never lives “all by itself.” All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.

Inventories / shop systems / character selectors all contain elements of:

- a database of items that you may possibly possess / equip
- a database of the items that you actually possess / equip currently
- perhaps another database of your “storage” area at home base?
- persistence of this information to storage between game runs
- presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
- interaction with items in the inventory or on the character or in the home base storage area
- interaction with the world to get items in and out
- dependence on asset definition (images, etc.) for presentation

Just the design choices of such a system can have a lot of complicating confounding issues, such as:

- can you have multiple items? Is there a limit?
- if there is an item limit, what is it? Total count? Weight? Size? Something else?
- are those items shown individually or do they stack?
- are coins / gems stacked but other stuff isn’t stacked?
- do items have detailed data shown (durability, rarity, damage, etc.)?
- can users combine items to make new items? How? Limits? Results? Messages of success/failure?
- can users substantially modify items with other things like spells, gems, sockets, etc.?
- does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
- etc.

Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

Breaking down a large problem such as inventory:

> [@Weapon Inventory and how to script weapons.](https://discussions.unity.com/t/826141/4):
>
> You’re welcome of course. One thing you could try to really get a “feel” for what happens in this case is make a simple script that is just one cell of your inventory. Put this into a script that you can access through an “inventory API” that does certain things to a cell. These functions might be: “Set the type of item” “Query the type and quantity of item in this cell” “Add 1 item to this cell.” “Add N number of items to this cell.” “Remove N item from this cell.” Then you can have pr…

If you want to see most of the steps involved, make a “micro inventory” in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

Everything you learn doing that “micro inventory” of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

Breaking down large problems in general:

> [@Options for implementing mining/digging in an asteroid belt game?](https://discussions.unity.com/t/908126/3):
>
> Whenever engineering seems too much to tackle, it's always best to see if you can break the problem down. What you describe above is by no means simple, as just the different ways all of it could be implemented are complex: does the camera rotate with the player on the asteroid? Do the player's controls rotate as they walk around the asteroid? Does the camera lock to the rotating asteroid? What does the camera do if the player digs down a ways? If the player digs a tunnel into the asteroid,…

Imphenzia: How Did I Learn To Make Games:

[![](https://europe1.discourse-cdn.com/unity/original/4X/8/e/8/8e89f6b74f09dc049f0792c06b2cd8dbcedeb9c5.jpeg "How did I learn to make Games?") ](https://www.youtube.com/watch?v=b3DOnigmLBY)

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. **Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.**  
**Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.**  
**BE PERFECT IN EVERYTHING YOU DO HERE!!**

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

**The complete error message contains everything you need to know to fix the error yourself.**

The important parts of the error message are:

- the description of the error itself (google this; you are NEVER the first one!)
- the file it occurred in (critical!)
- the line number and character position (the two numbers in parentheses)
- also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

**Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?**

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

---

<div class="post-metadata">

### Author: ![orionsyndrome](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/orionsyndrome/32/610667_2.png) [@orionsyndrome](https://discussions.unity.com/u/orionsyndrome)
#### Post date: [June 13, 2023, 2:42pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/3 "2023-06-13T14:42:15Z")

</div>

Well, think of it this way. You still need some way of specifying what ALL items means.  
So a collections of sorts is a must. Now the question becomes how to do it.

You can do (and this list is not exhaustive btw):

- group dragndrop all of them in the inspector MonoBehaviour
- group dragndrop all of them in the inspector ScriptableObject
- specify them in a txt/JSON/XML file, dragndrop that file, then parse this file
- specify them in an enum/array/List inside code
- load SOs via Resources or AssetBundles
- parse a JSON you get from a server or after running a query against a local SQL database
- ask the system to give you a list of files in a known folder

Or a combination thereof.

> [@ooffeekkii](#):
>
> should be arround 20 items and I might remove/add some later

If you need under 100 items, then a system like this one should suffice.

```auto
public interface IHasName {
  Name { get; }
}

```

```auto
using UnityEngine;

[CreateAssetMenu(fileName = "Item", menuName = "ScriptableObjects/New Item")]
public class ItemSO : ScriptableObject, IHasName {

  [SerializeField] string _name;
  [SerializeField] public int cost;

  public Name => _name;

}

```

```auto
using UnityEngine;

[CreateAssetMenu(fileName = "ItemArchive", menuName = "ScriptableObjects/New ItemArchive")]
public class ItemArchiveSO : ScriptableObject {

  public ItemSO[] Registry;

}

```

Once you create the file, lock the inspector on this, select all your other Item objects and dragndrop them into this field. Next, make a MonoBehaviour script to accept this unified access point

```auto
using System;
using System.Collections.Generic;
using UnityEngine;

public class GameInventory : MonoBehaviour, IEnumerable<ItemSO> {

  static GameInventory _instance;
  static public GameInventory Instance => _instance;

  [SerializeReference] ItemArchiveSO _items;

  Dictionary<string, int> _dict = null;

  void Awake() {
    _instance = this;
    buildDictionary();
  }

  void buildDictionary() {
    if(_items == null) return;
    for(int i = 0; i < _items.Registry.Length; i++)
      var item = _items.Registry[i] as IHasName;
      if(item != null) _dict.Add(item.Name, i);
    }
  }

  public ItemSO this[int index] {
    get {
      if(_items == null) throw new ArgumentOutOfRangeException();
      return _items.Registry[i] as ItemSO;
    }
  }

  public ItemSO GetByNameOrNull(string name) {
    if(_dict is null) return null;
    if(_dict.TryGetValue(name, out var index))
      return _items.Registry[index];
    return null;
  }

  public ItemSO this[string name] {
    get {
      if(_dict is null) return null;
      return _items.Registry[_dict[name]];
    }
  }

  public IEnumerator<ItemSO> GetEnumerator() {
    if(_items == null) yield break;
    for(int i = 0; i < _items.Registry.Length; i++)
      var item = _items.Registry[i] as ItemSO;
      if(item != null) yield return item;
    }
  }

  IEnumerator<ItemSO> IEnumerable<ItemSO>.GetEnumerator() => GetEnumerator();
  IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

}

```

Attach this to a permanent empty object in the scene. Drag your registry on to it. And you can now access this throughout your project like so

```auto
var inv = GameInventory.Instance;

var item = inv["JetPack"]; // would crash if JetPack wasn't present
Debug.Log($"Item with name {item.Name} has a cost of {item.cost}");

foreach(var item in inv) {
  Debug.Log(item.Name);
}

for(int i = 2; i < 8; i++) {
  var item = inv[i];
  Debug.Log($"Item at {i} is {item.Name}");
}

inv.GetByNameOrNull("item_that_doesnt_exist"); // wouldn't crash

```

That is unless there are errors in this code. I’m typing this directly in the browser.

---

<div class="post-metadata">

### Author: ![ooffeekkii](https://avatars.discourse-cdn.com/v4/letter/o/82dd89/32.png) [@ooffeekkii](https://discussions.unity.com/u/ooffeekkii)
#### Post date: [June 13, 2023, 3:10pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/4 "2023-06-13T15:10:58Z")

</div>

Thank you both for the response!  
I didn’t knew group dragndrop was an option (seen many totorials and no one used it, probabliy because of weights and probability)

additionaly, very impressive that you typed the code in the browser so quickly.

much appreciate!

---

<div class="post-metadata">

### Author: ![orionsyndrome](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/orionsyndrome/32/610667_2.png) [@orionsyndrome](https://discussions.unity.com/u/orionsyndrome)
#### Post date: [June 13, 2023, 4:31pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/5 "2023-06-13T16:31:29Z")

</div>

> [@ooffeekkii](#):
>
> I didn’t knew group dragndrop was an option

97% of the tutorials are really basic.

Here’s one showcasing group dragndrop explicitly

[https://www.youtube.com/watch?v=08\_giR06XwI](https://www.youtube.com/watch?v=08_giR06XwI)

---

<div class="post-metadata">

### Author: ![ooffeekkii](https://avatars.discourse-cdn.com/v4/letter/o/82dd89/32.png) [@ooffeekkii](https://discussions.unity.com/u/ooffeekkii)
#### Post date: [June 13, 2023, 5:04pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/6 "2023-06-13T17:04:55Z")

</div>

Thank you [orionsyndrome](https://forum.unity.com/members/orionsyndrome.620465/), I just tried it and I Iike the results.

I would be interested to hear what do you think about my second problem that I presented.  
currently I am thinking of giving each item an id and based on the id I will activate the appropriate function that does things. (kind of annoying since its another field I need to write)  
although I was also thinking It would be more clean If I will give each item a whole function as an attribute(I started reading about “delegate” in C#).  
are there other ideas or recommended conventions for my case?

---

<div class="post-metadata">

### Author: ![orionsyndrome](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/orionsyndrome/32/610667_2.png) [@orionsyndrome](https://discussions.unity.com/u/orionsyndrome)
#### Post date: [June 13, 2023, 5:57pm UTC](https://discussions.unity.com/t/loot-system-with-scriptable-objects/920502/7 "2023-06-13T17:57:31Z")

</div>

Ah yes sure, I forgot to tell you about that one and I planned to.

If your specific use case isn’t too specific or wild you might want to check out this article I wrote some time ago: [How to hook up functions from the inspector](https://forum.unity.com/threads/very-useful-reflection-pattern-injecting-function-from-a-static-library-by-string-name-and-more.843133/) .

Your implementation doesn’t necessarily have to be exactly like that, but it’s a neat concept to give you an idea.

The gist of it is to use reflection to dynamically bind a method which was originally referred to by a string.

So you serialize the “behavior” as a string, but it gets translated to proper function call in runtime. And this is done only once, so there is no real overhead. But because typing and maintaining strings is impractical, I then go extra mile and make a custom drawer which can sniff out the names from the actual class, and give you a dropdown in the inspector, so that you can choose a method like a boss.

That post is written as a “tutorial”, and if any of this sounds too complicated, I hope I’ve done a good job there, so make sure to read it whole.

Edit:  
Obviously you can make the delegate smarter, instead of it being `Func<string, string>` you can do something more appropriate, like

```auto
public delegate void TriggerBehavior(ItemSO item);

```

I should probably make a newer version of this tutorial. I might do this at one point given that this is actually a great way of associating serialized objects with runtime behaviors.
