How do I restrict what GameObjects can be assigned to a public field?

Let’s say I have a MonoBehavior called Player assigned to a GameObject. This script exposes a field named weapon, where one should assign a weapon game object - that is, a GameObject that has a script component that is a Weapon, another MonoBehavior.

Right now, what I do is expose the GameObject and anything can be assigned to it, so in the Start method I check if it was assigned and if the correct MonoBehavior is available. This approach means that I don’t get error checking during what I’d call “compile time”, only at startup.

Is there a technique to do this in Unity, specify that the GameObject should have an exact script or any other component assigned to it?

Replace GameObject with Weapon. This will mean that you will be assigning the weapon component that belongs to the GameObject instead of the Game Object itself. This means that you can only assign that particular component.

It would mean that you have to use weapon.gameObject (if the variable is called weapon) to get the Game Object that the weapon component belongs to though.