- Home /
How to create a script reference in the inspector that can accept any class of script?
I've made a system of for picking up items off the ground to use, which uses two seperate scripts that both respectively handle:
a) Picking the item up and attaching it to the player
b) The function that the item performs an action (Shooting, swinging, throwing, etc.)
The script that picks up the item contains a reference to the script that performs the action, so that the player can call the Use() function on it, which calls the Use() function on the script that contains the code for the action.
⠀
What I want to do is to have a reference to another script that is viewable in the inspector, so that I can reference any action script I want, and change them between instances of objects with the pickup script. If I make a reference for a singular class, eg public Pistol useWeapon
, it only allows for me to put in scripts called Pistol, but I want to be able to put in any script that derives from Monobehaviour.
Essentially, I want to know what I could replace "Pistol" with in the reference so that it accepts any script, so I can call the Use() function on said script.
⠀
I would also appreciate any suggestions of other methods of achieving the same outcome. Thanks in advance
Answer by ShadyProductions · Feb 04, 2020 at 03:09 PM
What you could do is use inheritance like:
public abstract class Weapon : MonoBehaviour
{
// Note that Weapon is abstract, so it cannot be directly assigned in the inspector.
// Only subclasses of Weapon can be assigned, like Pistol.
// If not all weapons need a custom class, you don't have to make it abstract.
public virtual void Use()
{
// Base logic for all weapons
}
}
public class Pistol : Weapon
{
public override void Use()
{
// Custom implementation of use for pistols
}
}
then you can assign objects like:
public Weapon useWeapon;
More on inheritance:
https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Script forgets assigned Inspector variables 2 Answers
Distribute terrain in zones 3 Answers
Modifying default Inspector GUI creator 3 Answers
Show custom List in Inspector? 1 Answer