Getting script from gameobject, but script name changes?

Hey guys, small problem here:
I have an interface script called Item.

Then I have many scripts called RedPotion, BluePotion, Boots, etc.

I am attaching the above scripts to empty game objects to use in an inventory system.

I use this:
GameObject.GetComponent();

I know that will give me the RedPotion script. The problem is that since its going to be an array of gameobjects, that object may not have a RedPotion script, it may have a BluePotion script, or Boot script, etc. Now, as I said earlier, they all implement the “Item” interface. If I use:

GameObject.GetComponent();

will that work? Will it pick up the script that implements Item, or does it look for a component called Item?

Sorry if i explained it badly, its hard to put this stuff into words.

What are you going to assign this to?

GameObject.GetComponent<Item>();

The above code, as you have posted, will return the ‘Item’ interface.

If you want to access the script of each item (take this with a grain of salt) you will have to check it, which seems like it will get out of hand.

Example:

    private GameObject[] Inventory;

    void Start ()
    {
        foreach (var item in Inventory)
        {
            Item currentSelection = item.GetComponent<Item>();

            if(currentSelection is Boots)
            {
                //do stuff
            }
           
            else if(currentSelection is Gloves)
            {
          
                //do something else
            }
            else if (currentSelection is RedPotion)
            {
          
                //do something else
            }
            //etc...
        }
    }

Then again I am not sure how you are tying this together, or why you want to access the script component of the gameobject.

You can access the properties or methods simply by:

currentSelection.PropertyFoo = "NewName";

//or

currentSelection.Foo();

However, if you want class specific content, such as a method defined in boots, you will need to cast it:

(currentSelection as Boots).BootsMethod();

//Similar for properties

(currentSelection as Boots).BootsProperty = value;

Yes.

Why didn’t you simply check that? You’ve gotta get into the mindset to check things that are simple to check! It won’t blow up your computer.

It will work, but Unity is not great with interfaces. Specially when trying to assign them in the editor. So if possible, use abstract classes instead.