Create a variable of type C# script?

Hi everyone!

In the game i’m making I have interactable objects (let’s say for now Doors and Chests).

I have a script that will find the nearest GameObject with the “interact” tag, and if it’s within a certain range it will search for the “proximity” script in the object and call a function.

And whenever i press “E” (if in range) it will call the “activate” function on the “proximity” script. This in turn should call the “objectInteract” function on a script i have in the gameObject. This script would change depending on the type of object it was (So Doors have the “door” script added through unity’s interface and Chests have the “chest” script added the same way.

My problem is that i can’t seem to find a way of having a public variable that will accept any kind of script for me to add through unity’s interface.
I know i can have say public ScriptName script, but i wanted a way to have public AnyScript script

Any idea if this is possible?

No.

However, the problem you’re describing can be solved using the OOP principle of polymorphism.

If you let “door” and “chest” both be derived from a common base class (call it “InteractiveObject”, say), and define objectInteract as a virtual method in the base class, that method can be overridden to act in different, specific ways in each derived class.

So have one base class attached to all interactive objects like this:

public class InteractiveObject
{
    // Virtual method 
    public virtual void objectInteract()
    {
        // Generic interactive stuff
    }
}

Then also attach a more specific derived class for each type of object such as:

public class Door : InteractiveObject
{
    public override void objectInteract()
    {
        // Specific Interaction code for doors...

        // If also want to call generic stuff then add
        base.objectInteract();
    }
}

or:

public class Chest : InteractiveObject
{
    public override void objectInteract()
    {
        // Specific Interaction code for chests...

        // If also want to call generic stuff then add
        base.objectInteract();
    }
}

You can now call the method from the base class script using GetComponent().objectInteract() on any object and it will actually execute the more specific derived class function depending on whether the object has the Door or Chest script attached.