Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Feature Request Applying stat value to weapons.

Discussion in 'Editor & General Support' started by OuterKnights, Aug 3, 2023.

  1. OuterKnights

    OuterKnights

    Joined:
    Jul 16, 2023
    Posts:
    28
    I have this stat system that I'm using in my game, I'm currently trying to pull a reference from the stat value and apply it to my weapons, but I honestly don't really know where to start.

    These are my script that handle this:

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Collections.ObjectModel;
    4.  
    5.  
    6.  
    7. [Serializable]
    8. public class CharacterStat
    9. {
    10.     public float BaseValue;
    11.  
    12.     protected bool isDirty = true;
    13.     protected float lastBaseValue;
    14.  
    15.     protected float _value;
    16.     public virtual float Value {
    17.         get {
    18.             if(isDirty || lastBaseValue != BaseValue) {
    19.                 lastBaseValue = BaseValue;
    20.                 _value = CalculateFinalValue();
    21.                 isDirty = false;
    22.             }
    23.             return _value;
    24.         }
    25.     }
    26.  
    27.     protected readonly List<StatModifier> statModifiers;
    28.     public readonly ReadOnlyCollection<StatModifier> StatModifiers;
    29.  
    30.     public CharacterStat()
    31.     {
    32.         statModifiers = new List<StatModifier>();
    33.         StatModifiers = statModifiers.AsReadOnly();
    34.     }
    35.  
    36.     public CharacterStat(float baseValue) : this()
    37.     {
    38.         BaseValue = baseValue;
    39.     }
    40.  
    41.     public virtual void AddModifier(StatModifier mod)
    42.     {
    43.         isDirty = true;
    44.         statModifiers.Add(mod);
    45.     }
    46.  
    47.     public virtual bool RemoveModifier(StatModifier mod)
    48.     {
    49.         if (statModifiers.Remove(mod))
    50.         {
    51.             isDirty = true;
    52.             return true;
    53.         }
    54.         return false;
    55.     }
    56.  
    57.     public virtual bool RemoveAllModifiersFromSource(object source)
    58.     {
    59.         int numRemovals = statModifiers.RemoveAll(mod => mod.Source == source);
    60.  
    61.         if (numRemovals > 0)
    62.         {
    63.             isDirty = true;
    64.             return true;
    65.         }
    66.         return false;
    67.     }
    68.  
    69.     protected virtual int CompareModifierOrder(StatModifier a, StatModifier b)
    70.     {
    71.         if (a.Order < b.Order)
    72.             return -1;
    73.         else if (a.Order > b.Order)
    74.             return 1;
    75.         return 0; //if (a.Order == b.Order)
    76.     }
    77.        
    78.     protected virtual float CalculateFinalValue()
    79.     {
    80.         float finalValue = BaseValue;
    81.         float sumPercentAdd = 0;
    82.  
    83.         statModifiers.Sort(CompareModifierOrder);
    84.  
    85.         for (int i = 0; i < statModifiers.Count; i++)
    86.         {
    87.             StatModifier mod = statModifiers[i];
    88.  
    89.             if (mod.Type == StatModType.Flat)
    90.             {
    91.                 finalValue += mod.Value;
    92.             }
    93.             else if (mod.Type == StatModType.PercentAdd)
    94.             {
    95.                 sumPercentAdd += mod.Value;
    96.  
    97.                 if (i + 1 >= statModifiers.Count || statModifiers[i + 1].Type != StatModType.PercentAdd)
    98.                 {
    99.                     finalValue *= 1 + sumPercentAdd;
    100.                     sumPercentAdd = 0;
    101.                 }
    102.             }
    103.             else if (mod.Type == StatModType.PercentMult)
    104.             {
    105.                 finalValue *= 1 + mod.Value;
    106.             }
    107.         }
    108.  
    109.         // Workaround for float calculation errors, like displaying 12.00001 instead of 12
    110.         return (float)Math.Round(finalValue, 4);
    111.     }
    112. }
    113.  
    114.  

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4.  
    5.  
    6. public class Character : MonoBehaviour
    7. {
    8.     public int Health = 50;
    9.  
    10.     public CharacterStat Strength;
    11.     public CharacterStat Agility;
    12.     public CharacterStat Intelligence;
    13.     public CharacterStat Vitality;
    14.  
    15.     [SerializeField] Inventory inventory;
    16.     [SerializeField] EquipmentPanel equipmentPanel;
    17.     [SerializeField] StatPanel statPanel;
    18.     [SerializeField] ItemTooltip itemTooltip;
    19.     [SerializeField] Image draggableItem;
    20.  
    21.     private ItemSlot dragItemSlot;
    22.  
    23.     private void OnValidate()
    24.     {
    25.         if (itemTooltip == null)
    26.             itemTooltip = FindObjectOfType<ItemTooltip>();
    27.     }
    28.  
    29.     private void Awake()
    30.     {
    31.         statPanel.SetStats(Strength, Agility, Intelligence, Vitality);
    32.         statPanel.UpdateStatValues();
    33.  
    34.  
    35.         inventory.OnRightClickEvent += Equip;
    36.         equipmentPanel.OnRightClickEvent += Unequip;
    37.  
    38.         inventory.OnPointerEnterEvent += ShowTooltip;
    39.         equipmentPanel.OnPointerEnterEvent += ShowTooltip;
    40.  
    41.         inventory.OnPointerExitEvent += HideTooltip;
    42.         equipmentPanel.OnPointerExitEvent += HideTooltip;
    43.  
    44.         inventory.OnBeginDragEvent += BeginDrag;
    45.         equipmentPanel.OnBeginDragEvent += BeginDrag;
    46.  
    47.         inventory.OnEndDragEvent += EndDrag;
    48.         equipmentPanel.OnEndDragEvent += EndDrag;
    49.  
    50.         inventory.OnDragEvent += Drag;
    51.         equipmentPanel.OnDragEvent += Drag;
    52.  
    53.         inventory.OnDropEvent += Drop;
    54.         equipmentPanel.OnDropEvent += Drop;
    55.     }
    56.  
    57.     private void Use(ItemSlot itemSlot)
    58.     {
    59.         if (itemSlot.Item is UsableItem)
    60.         {
    61.             UsableItem usableItem = (UsableItem)itemSlot.Item;
    62.             usableItem.Use(this);
    63.            
    64.             if (usableItem.IsConsumable)
    65.             {
    66.                 inventory.RemoveItem(usableItem);
    67.                 usableItem.Destroy();
    68.             }
    69.         }
    70.     }
    71.  
    72.  
    73.     private void Equip(ItemSlot itemSlot)
    74.     {
    75.         if (itemSlot.Item is EquippableItem)
    76.         {
    77.             Equip((EquippableItem)itemSlot.Item);
    78.         }
    79.     }
    80.  
    81.     private void Unequip(ItemSlot itemSlot)
    82.     {
    83.         EquippableItem equippableItem = itemSlot.Item as EquippableItem;
    84.         if (equippableItem != null)
    85.         {
    86.             Unequip(equippableItem);
    87.         }
    88.     }
    89.  
    90.     private void ShowTooltip(ItemSlot itemSlot)
    91.     {
    92.         if (itemSlot.Item != null)
    93.         {
    94.             itemTooltip.ShowTooltip(itemSlot.Item);
    95.         }
    96.         if (itemSlot.Item is UsableItem)
    97.         {
    98.             UsableItem usableItem = (UsableItem)itemSlot.Item;
    99.             usableItem.Use(this);
    100.            
    101.             if (usableItem.IsConsumable)
    102.             {
    103.                 inventory.RemoveItem(usableItem);
    104.                 usableItem.Destroy();
    105.             }
    106.         }
    107.     }
    108.  
    109.     private void HideTooltip(ItemSlot itemSlot)
    110.     {
    111.         itemTooltip.HideTooltip();
    112.     }
    113.  
    114.     private void BeginDrag(ItemSlot itemSlot)
    115.     {
    116.         if (itemSlot.Item != null)
    117.         {
    118.             dragItemSlot = itemSlot;
    119.             draggableItem.sprite = itemSlot.Item.Icon;
    120.             draggableItem.transform.position = Input.mousePosition;
    121.             draggableItem.enabled = true;
    122.         }
    123.     }
    124.  
    125.     private void EndDrag(ItemSlot itemSlot)
    126.     {
    127.         dragItemSlot = null;
    128.         draggableItem.enabled = false;
    129.     }
    130.  
    131.     private void Drag(ItemSlot itemSlot)
    132.     {
    133.         if (draggableItem.enabled)
    134.         {
    135.             draggableItem.transform.position = Input.mousePosition;
    136.         }
    137.     }
    138.  
    139.     private void Drop(ItemSlot dropItemSlot)
    140.     {
    141.         if (dragItemSlot == null) return;
    142.  
    143.         if (dropItemSlot.CanReceiveItem(dragItemSlot.Item) && dragItemSlot.CanReceiveItem(dropItemSlot.Item))
    144.         {
    145.             EquippableItem dragItem = dragItemSlot.Item as EquippableItem;
    146.             EquippableItem dropItem = dropItemSlot.Item as EquippableItem;
    147.  
    148.             if (dragItemSlot is EquipmentSlot)
    149.             {
    150.                 if (dragItem != null) dragItem.Unequip(this);
    151.                 if (dropItem != null) dropItem.Equip(this);
    152.             }
    153.             if (dropItemSlot is EquipmentSlot)
    154.             {
    155.                 if (dragItem != null) dragItem.Equip(this);
    156.                 if (dropItem != null) dropItem.Unequip(this);
    157.             }
    158.  
    159.             statPanel.UpdateStatValues();
    160.  
    161.             Item draggedItem = dragItemSlot.Item;
    162.             int draggedItemAmount = dragItemSlot.Amount;
    163.  
    164.             dragItemSlot.Item = dropItemSlot.Item;
    165.             dragItemSlot.Amount = dropItemSlot.Amount;
    166.  
    167.             dropItemSlot.Item = draggedItem;
    168.             dropItemSlot.Amount = draggedItemAmount;
    169.         }
    170.     }
    171.  
    172.  
    173.  
    174.     public void Equip(EquippableItem item)
    175.     {
    176.         if (inventory.RemoveItem(item))
    177.         {
    178.             EquippableItem previousItem;
    179.             if (equipmentPanel.AddItem(item, out previousItem))
    180.             {
    181.                 if (previousItem != null)
    182.                 {
    183.                     inventory.AddItem(previousItem);
    184.                     previousItem.Unequip(this);
    185.                     statPanel.UpdateStatValues();
    186.                 }
    187.                 item.Equip(this);
    188.                 statPanel.UpdateStatValues();
    189.             }
    190.             else
    191.             {
    192.                 inventory.AddItem(item);
    193.             }
    194.         }
    195.     }
    196.  
    197.     public void Unequip(EquippableItem item)
    198.     {
    199.         if (!inventory.IsFull() && equipmentPanel.RemoveItem(item))
    200.         {
    201.             item.Unequip(this);
    202.             statPanel.UpdateStatValues();
    203.             inventory.AddItem(item);
    204.         }
    205.     }
    206. }
    207.  
    208.  


    These scripts control this interface:
    Untitled.png


    I'm currently trying to figure out how to apply these values to my weapon, I know it's got to be somewhere in these two scripts but I can't pinpoint the right language.

    I've tried putting a public reference on my weapons public CharacterStat strength; and putting this on my weapons TakeDamage(10 + strength); but it doesn't seem to be the correct way to reference it.

    I want to pull from the value of the strength stat and add it to weapon damage so weapon damage grows with that stat but I can't seem to get the correct terminology, can someone explain to me how this should look? I'd really appreciate any constructive help to solve this.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    One stat at a time, just like you put your pants on! See video link at bottom. Keep asking yourself "Can I...??"

    First, figure out what you mean by "Apply." Usually this means "take some value and transiently adjust it for XXX." In this case XXX could be "for me to use" or "for other systems to observe,", etc.

    That can help you reason more clearly about the flow of the data, which is the only thing that matters.

    These things (inventory, stat systems, 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:

    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.

    Breaking down large problems in general:

    https://forum.unity.com/threads/opt...n-an-asteroid-belt-game.1395319/#post-8781697

    The moment you put an inventory system into place is also a fantastic time to consider your data lifetime and persistence. Create a load/save game and put the inventory data store into that load/save data area and begin loading/saving the game state every time you run / stop the game. Doing this early in the development cycle will make things much easier later on.

    Imphenzia: How Did I Learn To Make Games:



    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.