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 Getting type error

Discussion in 'Scripting' started by universiti_com, Jul 31, 2023.

  1. universiti_com

    universiti_com

    Joined:
    Jan 5, 2022
    Posts:
    11
    Hi All,

    I'm trying to resolve a type error. On the line "itemImLookingFor = go", it gives me a type conversion error and, for the life of me, I can't figure out how to convert/resolve it:

    Code (CSharp):
    1.             Item itemImLookingFor = null;
    2.             GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag("InventoryItem");  //Find all GameObjects with specific tag
    3.  
    4.             foreach (GameObject go in taggedObjects)  //iterate through all returned objects, and find the one with the correct tag
    5.             {
    6.                 if (go.tag == "InventoryItem")
    7.                 {
    8.                     itemImLookingFor = go;
    9.                     Debug.Log("found " + itemImLookingFor.name);
    10.  
    11.                     slots[i].Add(itemImLookingFor);
    12.                     i++;
    13.  
    14.                     // break;
    15.                 }
    16.             }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    itemImLookingFor is of type Item
    go is of type GameObject

    Do you see why that doesn't work?

    Does go have an Item script on it? If so, then you need to use GetComponent to get the Item script off of it and tie that to the variable.
     
    Bunny83 and spiney199 like this.
  3. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    If "Item" is a class you made, and is on said gameObjects you're finding, just change:
    Code (CSharp):
    1. itemImLookingFor = go.GetComponent<Item>();
    I used to hate using GetComponent() during runtime, so it is odd recommending it. But it primarily can be useful if said object has multiple scripts attached, and you only want a particular script in return.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563