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

Should I use the same script to Use Item for each different item?

Discussion in 'Scripting' started by DarkEcho, Oct 6, 2014.

  1. DarkEcho

    DarkEcho

    Joined:
    Jul 7, 2014
    Posts:
    231
    I have a script which is being used for every item with different variable values (Item name = Iron Ingot)

    Would it be ok to also code how the item is used in the same script?

    Bear in mind this script is being used with every item, the variables are just modified to the correct value for usage.
     
  2. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    yes and that would make your project more manageable as well. You don't need 500 copies of the script that does the same thing. Reuse when possible.
     
  3. DarkEcho

    DarkEcho

    Joined:
    Jul 7, 2014
    Posts:
    231
    Thanks, so just adding how each item is used to the script for every item (Still in the same script) shouldnt cause any issues at all?
    Just want to make sure im on the right path :)
     
  4. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    No, THAT would get unmanageable. If all your items share a common functionality, create an abstract class which will be the parent to all items.

    Then just have a virtual method within the parent such as "UseItem"...then whenever you want to create a new type of item, create a new script , inherit from the base class, and override the UseItem function.

    Code (CSharp):
    1.  
    2. abstract class Item : MonoBehavior
    3. {
    4.   protected float m_price;
    5.  
    6.   protected virtual void UseItem(){}
    7.   protected virtual string GetStats(){return "";}
    8. }
    9.  
    10. class IronIngot : Item
    11. {
    12.   protected override void UseItem()
    13.  {
    14.   //what happens if you use this item
    15.  }
    16.  
    17.  protected override void GetStats()
    18.   {
    19.     //print things like this specific item name, any stats only this type of item should have etc.
    20.   }
    21. }
    22.  
     
  5. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Yeah if every item behaves differently you don't want to do that... either use an interface or an abstract class and create classes for your items.