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

Question How to set Item active, when it is highlighted?

Discussion in 'Scripting' started by Media_Malte, Jun 19, 2023.

  1. Media_Malte

    Media_Malte

    Joined:
    Jul 27, 2022
    Posts:
    18
    So I followed this Tutorial about making an Inventory System and everything works fine, but now after the vid, I dont know how to really use the stuff he made me do. So in the Script down there we made a Function that is called "GetSelectedItem" and I think thats what I need to use in the other script, that will say: if selected Item = sword {make this GameObject active} else {disable this GameObject}. But I really tried and could not figure out how to do that. I bet it is really simple but I tried my best and it does not work.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class InventoryManager : MonoBehaviour
    6. {
    7.     public static InventoryManager instance;
    8.     public int maxStackedItems = 999;
    9.     public InventorySlot[] inventorySlots;
    10.     public GameObject inventoryItemPrefab;
    11.     int selectedSlot = -1;
    12.     private void Awake()
    13.     {
    14.         instance = this;
    15.     }
    16.     private void Start()
    17.     {
    18.         ChangeSelectedSlot(0);
    19.     }
    20.     private void Update()
    21.     {
    22.         if (Input.inputString != null)
    23.         {
    24.             bool isNumber = int.TryParse(Input.inputString, out int number);
    25.             if(isNumber && number > 0 && number < 4)
    26.             {
    27.                 ChangeSelectedSlot(number - 1);
    28.             }
    29.         }
    30.         float scroll = Input.GetAxis("Mouse ScrollWheel");
    31.         if (scroll != 0)
    32.         {
    33.             int newValue = selectedSlot - (int)(scroll / Mathf.Abs(scroll));
    34.             if (newValue < 0)
    35.             {
    36.                 newValue = inventorySlots.Length - 1;
    37.             }
    38.             else if (newValue >= inventorySlots.Length)
    39.             {
    40.                 newValue = 0;
    41.             }
    42.             ChangeSelectedSlot(newValue % 3);
    43.         }
    44.     }
    45.     void ChangeSelectedSlot(int newValue)
    46.     {
    47.         if(selectedSlot >= 0)
    48.         {
    49.             inventorySlots[selectedSlot].Deselect();
    50.         }
    51.         inventorySlots[newValue].Select();
    52.         selectedSlot = newValue;
    53.     }
    54.  
    55.     public bool AddItem(Item item)
    56.     {
    57.         for (int i = 0; i < inventorySlots.Length; i++)
    58.         {
    59.             InventorySlot slot = inventorySlots[i];
    60.             InventoryItem itemInSlot = slot.GetComponentInChildren<InventoryItem>();
    61.             if (itemInSlot != null && itemInSlot.item == item && itemInSlot.count < maxStackedItems && itemInSlot.item.stackable == true)
    62.             {
    63.                 itemInSlot.count++;
    64.                 itemInSlot.RefreshCount();
    65.                 return true;
    66.             }
    67.         }
    68.  
    69.         for (int i = 0; i < inventorySlots.Length; i++)
    70.         {
    71.             InventorySlot slot = inventorySlots[i];
    72.             InventoryItem itemInSlot = slot.GetComponentInChildren<InventoryItem>();
    73.             if (itemInSlot == null)
    74.             {
    75.                 SpawnNewItem(item, slot);
    76.                 return true;
    77.             }
    78.         }
    79.         return false;
    80.     }
    81.     void SpawnNewItem(Item item, InventorySlot slot)
    82.     {
    83.         GameObject newItemGo = Instantiate(inventoryItemPrefab, slot.transform);
    84.         InventoryItem inventoryItem = newItemGo.GetComponent<InventoryItem>();
    85.         inventoryItem.InitializeItem(item);
    86.     }
    87.  
    88.     public Item GetSelectedItem(bool use)
    89.     {
    90.         InventorySlot slot = inventorySlots[selectedSlot];
    91.         InventoryItem itemInSlot = slot.GetComponentInChildren<InventoryItem>();
    92.         if (itemInSlot != null)
    93.         {
    94.             Item item = itemInSlot.item;
    95.             if(use == true)
    96.             {
    97.                 itemInSlot.count--;
    98.                 if(itemInSlot.count <= 0)
    99.                 {
    100.                     Destroy(itemInSlot.gameObject);
    101.                 }
    102.                 else
    103.                 {
    104.                     itemInSlot.RefreshCount();
    105.                 }
    106.             }
    107.            
    108.             return item;
    109.         }
    110.         return null;
    111.     }
    112.  
    113. }
    114.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    What Gameobject?

    The Button?

    The graphic on the button?

    A highlight on the button?

    The item in your hand or in the actual game?

    Every one of these is a different answer... inventories are CRAZY complex.

    Either way, when you decide, use
    GameObject.SetActive(true)
    on the one you want.

    These things (inventory, 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
     
  3. Media_Malte

    Media_Malte

    Joined:
    Jul 27, 2022
    Posts:
    18
    Hi again, so here in this Video I show you the Problem. I want the Axe on the Player only to be shown, when the Axe is in the Selected Slot. Otherwise this GameObject should be Disabled. I have the Axe as an Item Prefab, and as another GameObject for the actual axe on the Player
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    If you haven't finished making this portion of the inventory system, again, there is nothing I can type in this box to help you. All I can say is, as I suggested above, work through some tutorials on inventories. These can can show you some of the approaches for accomplishing all parts of what you have designed.

    If you think you HAVE finished this function, then you have a bug and that can only mean...

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.