Search code examples
c#objectunity-game-engineinventory

Getting C# object reference in Unity3D


I want to get C# object in unity by clicking on it. I made ray and it works properly. Problem is in copying object. I'm making something like inventory system. All of my collectable items have item scripts with variables like name or ID. For getting C# object of script from gameobject I'm using

itemList.Add (hitInfo.transform.gameObject.GetComponent<Item> ()); // adding C# object to C# List

and then I destroy gameobject (maybe it's a problem), but when i try print something like itemList[0].name it's not work because of: "NullReferenceException: Object reference not set to an instance of an object" It's caused by destroing object? Or I should just copy reference of the object in other way (by not using itemList.Add (hitInfo.transform.gameObject.GetComponent<Item> ()))?

EDIT://Exception appearce even if I don't destroy the gameobject. EDIT2://When I start game and check itemList.Count; (it should show the number of elements in the list I think) it's 15 not 0 and I don't know why.


Solution

  • From my understanding, the code you posted is getting the "Item" component from the object you click on. A component instance MUST have a single object that it is associated with. So when you delete the object, you are also deleting the "Item" component on that object.

    What you should really do is have a data model class for the item as a Field on the component. This class would contain whatever data (name, is required by your inventory. So instead of adding the Item component to the list you would add the data model. The reference to this model class will persist when the GameObject is deleted.

    public class Item : MonoBehaviour
    {
        [System.Serializable]
        public ItemModel Model;
    }
    
    public class ItemModel
    {
        public string Name;
        public int Id;
    }
    

    Get it like this:

    gameObject.GetComponent<Item>().Model