Jump to content
  • Advertisement
SongOfDurin

Unity Item representation in Unity

Recommended Posts

Hi all,

I´m currently working on a little 2D "explorer game" in Unity and do have some problems with the item database.

First I created a simple XML Database in which I stored things like ItemValue, ItemDescription.....and also the Path to the specific prefab. Because I wanted to manage my Database only in one place, I started to build a Custom Editor and used Scriptable Objects to represent my desired Item Hierarchy.

At this point I learned a lot about Unity´s crappy serialization system and how you have to do "big" workarounds to save your Database without any restriction like "No support for custom null classes, no support for polymorphism....) .

I started to realize that I have to setup my own little "system" to get the job done but I can´t get my head around the whole thing.

 

1) Lets say I have the raw data representation of my Items (ItemID, ItemDescription, ItemValue e.g) saved  in a .json or .yaml file, how do I map the "raw data" to the visual part of the item (in game)?

    Should I create the Items dynamically (e.g create some factorys for diffrent item types and build them in code)?

    Should I rewrite my "custom editor" to create acutal  prefabs and save the path to my desired item like I did in the XML thing?

    Is there an best practice for this kind of problem in Unity?

 

Kind regards,

   

 

 

Share this post


Link to post
Share on other sites
Advertisement

You probably do want some sort of factory, yeah. For example, your database might include a field like "InGame Prefab Name", which your factory can use to look up the relevant object to Instantiate. Your factory itself might just be a MonoBehavior with an array of prefabs, and you can iterate through them at runtime to find them by name.

Something you didn't mention, but which is important to think about, is to have a clear understanding about the difference between an item instance and an item type (also known as an item definition, or an item archetype, or similar). For example, you might have 1 row or definition for the type, which has the basic properties, the name of the prefab to be used, etc - but that doesn't tell you where you might find instances of that object in the game. That would probably be in a different table entirely, or handled via a different system (e.g. a 'spawn' system), which creates item instances in the world given an item type and a position.

Share this post


Link to post
Share on other sites

Hi Kylotan,

thanks for your reply.

At the moment I have an abstract class called "BaseItem" which serves as the base of all evil.

The classes Consumable, Obstacle and Material inherit from the root class. 

All items share some base information like ItemID, ItemName, ItemDescription, ItemValue, QuestItem and the child classes have some extra functions, extra fields ect...

Now I can use JSONUtility or the YAMLDotNet Library to de/serialize all that stuff and create objects in code. If Iuse the .json format I could go further and use MongoDB to manage all that stuff (for example).

But thats only the "definition" of the items and the way I save them on the disk.

Now imagine I load my Database in some sort of data structure when the game starts which gives me the possibility to iterate through all my items at runtime or do other fancy stuff.

The next step could be an abstract Item Factory. 

If I want to spawn a mushroom  I could say  "Hey Consumable Factory, create some nice mushrooms for me".

Then the spawn system can get some sort of notification to spawn that shit at position X/Y.

 

Now I try to ask my question in a diffrent way:

Should I create the prefabs for each Item manually and save only the paths into my database so that I can do something like this:

Instantiate(Ressources.Load<SomeType>(SomeType.prefabPath)) OR

Should I create the "game objects" dynamically with some sort of factory like:

Okay Consumable Factory, I need a mushroom and a mushroom needs a Rigidbody2D, a BoxCollider and a SpriteRenderer.

 

 

 

 

 

 

 

Share this post


Link to post
Share on other sites

I would recommend that you create the prefabs manually, assign them into some object in the inspector, and use that object at run time to look up the prefabs that you want to spawn. Resources.Load is not a good system to use, generally.

You don't need to construct the object component-by-component; the Unity prefab system exists entirely so you don't have to do that.

Share this post


Link to post
Share on other sites

Hey Kylotan thanks for your reply and sorry for my absence!!!

I think something is wrong with my brain or with Unity.

It´s true, Unity´s Prefab System exists to hold the recipes for specific entities but I can hardly believe that adding thousands of prefabs to a GameObject is the right way.

Many developers from which I have read the dev. log used databases like MongoDB, SQLLite, CouchDB or what ever to store their data...so there must be a way or a pattern to associate the metadata from  my  items (damage, defense, special effects...) with specific prefabs/objects in Unity.

The only way I can think of to achieving this is to create the prefab through a custom editor and save all paths into my item and serialize it or create a component system and add only a "prefab component" to items which need a visual representation (and save all relevant infos in this specific component)

 

Would this be a valid option too?

 

 

Edited by SongOfDurin

Share this post


Link to post
Share on other sites

Firstly, most single player games don't have thousands of item types, so the problem of scale you mention never comes up. They might have a few hundred, but it's not a hardship to add them to a game object one by one, any more than it would be a hardship to add them to a database one by one.

Secondly, developers that are using MongoDB or CouchDB for their data are typically working on online games. You don't use this for client-side data because you aren't going to ship an instance of Mongo with your game! Nor are clients going to connect to a shared database. When working on a persistent online game the database is made necessary by other constraints, and given that they already have a database connected, it can make sense to extend that usage to include storing their object types. But again, that is for online server-side data, not for client-side data. (If you have some specific articles you've seen, feel free to link them and we can discuss what they're doing.)

SQLite, however, can be a good solution for client-side data. It makes a lot of sense for multiplayer games when you maybe have an SQL database on the server and you can get some benefits from having a very similar table structure on the client, allowing you to share identifiers and maybe some code. If you don't have the server, these benefits disappear, so you have to consider whether SQLite gives you anything useful. In the case of Unity, the answer is often no. Unity's serialisation system and prefabs already give you a decent interface for adding, editing, and storing your game data in the editor.

What is the reason you have for wanting to define your item properties separately from the Unity data? Is it a multiplayer game? Do you have a separate tool that you'd prefer to use? You can export that data in whatever form you like but ultimately you're going to want a process of matching up Unity prefabs to item properties and that's where a name=>prefab database comes in, whether that is an array of Gameobjects or a wrapper around Resources.Load or access within an AssetBundle or similar. Even if you had an SQLite DB locally which contains your object data, you still need a routine that finds the prefabs accordingly, and then, most likely, injects the information from the database into the in-game objects. Often that is more complex than just defining the data in Unity directly!

Share this post


Link to post
Share on other sites
On 17.8.2017 at 11:14 AM, Kylotan said:

What is the reason you have for wanting to define your item properties separately from the Unity data? Is it a multiplayer game? Do you have a separate tool that you'd prefer to use? You can export that data in whatever form you like but ultimately you're going to want a process of matching up Unity prefabs to item properties and that's where a name=>prefab database comes in, whether that is an array of Gameobjects or a wrapper around Resources.Load or access within an AssetBundle or similar. Even if you had an SQLite DB locally which contains your object data, you still need a routine that finds the prefabs accordingly, and then, most likely, injects the information from the database into the in-game objects. Often that is more complex than just defining the data in Unity directly!

Because Unitys serialization system sucks as hell. In my opinion it is not really possible to write object oriented C# Scripts when Unity is not be able to serialize custom classes/generics without hacking something together like there is no morning. Therefor it shouldn´t be more complex then writing my own system especially when there are libraries like Json.NET which has very cool features for JSON serialization.

But no matter which system I use, the 

Quote

a routine that finds the prefabs accordingly, and then, most likely, injects the information from the database into the in-game objects

make me some headache because I don´t know how to connect the "raw data" with the prefabs/gameobjects properly.

Maybe my english is to bad to express my exact problem.

**Edit

https://feedback.unity3d.com/suggestions/serialization-of-polymorphic-dat

Some inspiration from other developers

Edited by SongOfDurin

Share this post


Link to post
Share on other sites

Unity's serialisation has problems, sure. But there's one thing it can do quite easily, and that's represent simple tables of data - which is pretty much exactly what you'd have with an external database.

To be fair serialising generics is a hard problem in most languages. I don't think UE4 can do a great job of it either. This is very separate from your data model, where the concept of generics does not (or at least should not) exist.

I already explained how to connect the raw data with the game objects, so if that doesn't work for you, you will have to tell us why not, then we can suggest a different approach.

As a reminder, the process can be quite simple:

  • Option 1: a gameobject with a list of prefabs, which you populate via the Inspector in the editor. You can iterate through them and pick the right one out by name. These names are stored in your item data. (e.g. {"name": "Sword", "Weight": 10, "Prefab": "Sword123"} )
  • Option 2: prefabs stuffed into a Resources directory. You take the name from your item data and get the prefab via Resources.Load. You probably want to use a filename instead of some other name.

None of this particularly cares about how you choose to store your item data - you seem determined to use an external data format or database, and that is your choice, but as long as you include some sort of identifier to look up a prefab, there should be no problem.

 

15 minutes ago, SongOfDurin said:

Maybe my english is to bad to express my exact problem.

Sprichst du Deutsch? Dein Englisch ist gut (im Gegensatz zu mein Deutsch), doch dein Problem ist unklar...

Share this post


Link to post
Share on other sites

Ja ich spreche Deutsch :).

I think I mentioned your Option 2 in one of my last posts 

Quote

The only way I can think of to achieving this is to create the prefab through a custom editor and save all paths into my item and serialize it 

With this approach I should be able to centralize my Prefab/Item creation. Then I could use my "item name" or "item id" as the key value and access the prefab over the prefab path in my specific item. But it seems really odd to do this.

As I started with Unity I programmed a custom editor and used Scriptable Objects for my class hierarchie. The bad thing about this was the fact that I had to save every Item Instance as an asset to my "asset database" and after I switched my base class to an abstract base class I got a big surprise: It roasted my whole database. While researching this stuff I decided to to avoid as much as possible because with other serialization technics I get the same resul, with much less effort.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By Alexander_Vovk
      Hello Guys!
      Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
      Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
      Thank you
      Best Regards
      Alex Vovk
      Co-Founder of Sixteen Squares
      Alexander_Vovk@outlook.com
       
    • By RoKabium Games
      Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!
    • By JoshuaFraser
      Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }  
    • By Erik Nivala
      So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
      Is there a "standard" way that this is usually done that i am missing?
      I am fairly new to programming so any help is appreciated!
    • By MintyLyton
      I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website. 
    • By ethancodes
      I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
      Here is the code for the pick up manager:
      // Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
      public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }  
      There is also a Base Pick Up:
      public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed. 
    • By D34DPOOL
      Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
      Posted by D34DPOOL on May 20th, 2018
      Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
      What is required:
      Skill using C#
      Experience with Unity
      Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
      Compensation:
      Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
      It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!
       
      To apply email me at mangemason@yahoo.com
    • By davejones
      Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

      Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
    • By MoreLion
      hey all! We are looking for members for our Unity horror game! 
      Here’s the story:
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
      This game is not a long development game, I have loads other game ideas,
      I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
      And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
      There is some concept art one of our concept artists have made
      If interested email liondude12@gmail.com
    • By Canadian Map Makers
      GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

      Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.

       

      We would like programmers and graphical artists to come onboard to (initially) create:

      A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
      A module where city infrastructure can be built on a real 3D interactive landscape.
      For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.

       

      More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).

       

      This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.

       

      Best regards,

      Steve Chapman (Canadian Map Makers)

       
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631398
    • Total Posts
      2999838
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!