Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How do I make a harvesting system for a survival game?

Discussion in 'Scripting' started by Wavvyy, Dec 5, 2022.

  1. Wavvyy

    Wavvyy

    Joined:
    Nov 4, 2022
    Posts:
    4
    I'm currently experimenting and learning in unity and I decided to make a survival game prototype for fun. I'm new to scripting in general and I wondered how I could make a proper harvesting system. This is what I have done so far.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem.HID;
    5.  
    6. public class PlayerHarvest : MonoBehaviour
    7. {
    8.     public int Gold = 0;
    9.     public int Iron = 0;
    10.     public int Bronze = 0;
    11.  
    12.     public float cooldown = 1f;
    13.     private bool cool = true;
    14.  
    15.     public Resources Resources;
    16.  
    17.     public LayerMask groundMask;
    18.     public Camera playerCamera;
    19.  
    20.     private float distance = 2f;
    21.     private bool harvestKeyPressed;
    22.  
    23.     public void coolDownStart()
    24.     {
    25.         StartCoroutine(CoolDownCoroutine());
    26.     }
    27.     IEnumerator CoolDownCoroutine()
    28.     {
    29.         cool = false;
    30.         yield return new WaitForSecondsRealtime(cooldown);
    31.         cool = true;
    32.     }
    33.  
    34.  
    35.     private void Update()
    36.     {
    37.  
    38.         harvestKeyPressed = Input.GetKeyDown(KeyCode.Mouse0);
    39.  
    40.         Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
    41.  
    42.         if (harvestKeyPressed)
    43.         {
    44.             if (Physics.Raycast(ray, out RaycastHit hitinfo, distance, groundMask) && cool == true)
    45.             {
    46.                 coolDownStart();
    47.                 Resources.ResourceHarvested();
    48.             }
    49.          
    50.         }
    51.      
    52.     }
    53.  
    54. }
    Here is the "Resources" script

    Code (CSharp):
    1. public class Resources : MonoBehaviour
    2. {
    3.     public int resourceReturnIron = 5;
    4.     public int resourceReturnGold = 5;
    5.     public int resourceReturnBronze = 5;
    6.  
    7.     public PlayerHarvest resourceReturn;
    8.     public int hitPoints = 5;
    9.  
    10.     public void ResourceHarvested()
    11.     {    
    12.         hitPoints -= 1;
    13.  
    14.         if (tag == "Iron")
    15.         {
    16.             Debug.Log("You Harvested Iron");
    17.             resourceReturn.Iron += resourceReturnIron;
    18.         } else if (tag == "Gold")
    19.         {
    20.             Debug.Log("You Harvested Gold");
    21.             resourceReturn.Gold += resourceReturnGold;
    22.         } else if (tag == "Bronze")
    23.         {
    24.             Debug.Log("You Harvested Bronze");
    25.             resourceReturn.Bronze += resourceReturnBronze;
    26.         }
    27.     }
    28.  
    29.     private void Update()
    30.     {
    31.         if (hitPoints == 0)
    32.         {
    33.             if (tag == "Iron")
    34.             {
    35.                 Destroy(GameObject.FindWithTag("Iron"));
    36.             }
    37.             else if (tag == "Gold")
    38.             {
    39.                 Destroy(GameObject.FindWithTag("Gold"));
    40.             }
    41.             else if (tag == "Bronze")
    42.             {
    43.                 Destroy(GameObject.FindWithTag("Bronze"));
    44.             }
    45.         }
    46.     }
    47.  
    48. }
    The current errors I have is that I can only harvest one resource because I'm using a reference to one script on one resource.
    After this I have to add an inventory and make it so resources actually show up in your inventory etc. How would I go on about this? Keep in mind that I'm still a beginner -- Thanks for listening.
    Here is a little preview:
     
    Last edited: Dec 5, 2022
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,609
    A honest answer is... by learning more Unity and C# in general. Inventories and crafting is pretty complicated, somewhat advanced stuff. Kudos for aiming for the stars but don't be discouraged when you find this style of stuff particularly difficult.

    But to give some direction, obviously a direct reference between two monobehaviours isn't going to work. You're going to need more flexible means of interaction between various game play elements. This depends greatly on the style of game (fps, 3ps, isometric, etc). Figure how you want this to work, then research how to do that. That's all I can say considering I don't know anything else about your game aside from these two scripts.

    You'll also want to learn about how to use serialisable plain C# classes, and scriptable objects. You won't be able to make a functioning inventory without the both of those.
     
    Niter88 likes this.
  3. Wavvyy

    Wavvyy

    Joined:
    Nov 4, 2022
    Posts:
    4
    Hello spiney199! Thanks for your answer, I didn't know adding this would be so hard! I still want to attempt It keeping in mind this is just a test project, it's all a learning process! I will upload a video of how my game looks so far to give a better representation of what I need.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    As Spiney points out, these things (inventories, shop systems, character customization, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

    They 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 an inventory 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:

    https://forum.unity.com/threads/weapon-inventory-and-how-to-script-weapons.1046236/#post-6769558

    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.

    Your best bet is to do at least THREE widely-different inventory system tutorials and to do them correctly so that you identify all parts relevant to this complex problem space.

    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!
     
    Niter88 likes this.
  5. Wavvyy

    Wavvyy

    Joined:
    Nov 4, 2022
    Posts:
    4
    Hello Kurt Dekker, Thanks for your response! I certainly think I will put my survival game project to rest for now and start learning! I'm going to start off by watching more tutorials on C# alone and after that I will start watching more unity tutorials and do exactly what you said. This will take some time but worth it for the knowledge.
    I must say I got very excited when you listed all of the things I needed to do to make inventory work, it just sparked my creativity. Programming is so fun and I can't wait to learn more!
     
    Niter88 and spiney199 like this.
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    You're going to go a long way with this great attitude. Programming is a lifetime challenge, you will always be learning more and more things as long as you fearlessly go towards them.

    Remember that what I list above is the biggest possible set of things for an inventory.

    You could still make an ULTRA simple inventory where you hold just two items, one in each hand, just by putting two buttons with images in the upper corner of the screen and having them able to hold one thing each. I know that's not nearly enough for a survival game, but it could be a start.
     
    koirat and Niter88 like this.
  7. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,910
    The next step would be to shift your Resources script onto the objects themselves. That way each will have it's own "hitPoints".

    Then do something like hitInfo.GetComponent<Resource>().Harvested(); on the player.
     
  8. Niter88

    Niter88

    Joined:
    Jul 24, 2019
    Posts:
    112
    gonna place a ward here for later
     
  9. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    So a good inventory is highly game specific. Same as pickups so not all pickups are the same some guy likes to do certain things that make his:her pick up and inventory unique :] but the basis of most inventory is the memory of the contents of that inventory, one; of the things that become memory; two; of the the things when they are in memory. I know the choice of words may not be the clearest. But it is all about collecting data, holding data in a sorted list, and then displaying data. This is your inventory. As Kurt said it can be two hands, two slots. Or it can be 10 hands and 20 slots :[ you can have a list for a large inventory or you can have a couple of slots of a small inventory. The question everyone wants to know before providing any direction here is surely the scope of the inventory. That is what should the end result of the inventory be. What behaviours and how much. Does my bag have 8 slots for inventory. But I pick up another bag has 27 slots of inventory. Is the inventory just a tab menu with always the same values?
    it is a guessing game and I am a wishing man.