Search Unity

Help function parameter

Discussion in 'Scripting' started by henmachuca, Mar 1, 2018.

  1. henmachuca

    henmachuca

    Joined:
    Oct 14, 2016
    Posts:
    105
    Hello,

    I have a base classe called ITEM and a class derived from it called EQUIPMENT.

    In my EquipmentManager class I have a Equip method that takes an equipment as parameter
    In my inventory class,
    I also have a method that swap the items whenever i'm trying to swap the inventory slot with the character panel slot (the one where you see what gear is equipped).

    The thing is that when I swap items, Im calling the equip method, but unity complains that it cant convert items to equipment. (Line 8 of my first code).

    Code (CSharp):
    1. public class SlotV2 : MonoBehaviour, IPointerClickHandler
    2. {
    3.         public static void SwapItems(SlotV2 from, SlotV2 to)
    4.         {
    5.             Stack<Item> tmpTo = new Stack<Item>(to.items);
    6.  
    7.             to.AddItems(from.items);
    8.             EquipmentManager.instance.Equip(from.CurrentItem);
    9.         }
    10. }
    Code (CSharp):
    1.   // Equip a new item
    2.     public void Equip(Equipment newItem)
    3.     {
    4.        
    5.     }
    Can anyone offer me some help of how can I solve this?
    I change the parameters of the Equip function because equipment has some variables that I need for that function like skinned mesh and others.

    Thank you.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    An equipment is an item but an item isn't necessarily an equipment. You'll need to cast to the appropriate type. I think it makes the most sense to change the Equip function's signature to use an item, rather than making the assumption that any items you swap are equipment.

    Code (csharp):
    1.  
    2. public void Equip(Item newItem)
    3. {
    4.    Equipment equipment = newItem as Equipment;
    5.    if(equipment != null)
    6.    {
    7.        // do whatever
    8.    }
    9.    else
    10.    {
    11.       Debug.Log("Error: Attempted to equip non-equipment item.");
    12.    }
    13. }
    14.  
     
    henmachuca likes this.
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You can use 'as' to cast your Item to equipment. If it's non-null, you can pass the new variable to your Equip method.

    Edit: even better -with an example - above ;)
     
    henmachuca likes this.
  4. henmachuca

    henmachuca

    Joined:
    Oct 14, 2016
    Posts:
    105
    Awesome! Thank you @GroZZleR, didn't know that kind of functionallity. How is that called so I can look this up a bit more in depth?

    By the way... The solution worked perfectly!!
    Thank you too @methos5k
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You could look up 'casting' and the ''as' operator' :)
     
    henmachuca likes this.