In my game, I have a bunch of objects the player can interact with to varying degrees. I have implemented this in C# scripts using the following general hierarchy:
// to define basic methods for looking at, picking up etc.
public abstract class Interactible: MonoBehaviour
// a concrete Interactible
public class SomeObject: Interactible
// to define an extra method Use() for objects that can be used on something else later on
public abstract class Usable: Interactible
// concrete usables
SomeSpecialObject: Usable
SomeOtherSpecialObject: Usable
I have another script called ObjectManager that takes responsibility for displaying the interaction interface to the player, depending on how the player is currently relating to the object and what type of object it is.
e.g.1 if they’ve just walked up to it, it displays an image of the xbox controller button mapping to pick up
e.g.2 if they’ve already picked it up, it displays the buttons mapping to use or drop etc
I want every object to have an objectmanager script. So I want to create it once as a protected variable in Interactible and never have to worry about it again.
How can I programatically assign a script as a variable inside another script? Does the fact that the base script in which I want to do this is abstract and not attached to any game objects itself change anything?
I’ve tried:
i) declaring the protected script variable inside Interactible and calling GetComponent() in the Awake() method, but Unity says it is not instantiated when I try to use it in the concrete derived classes later on in their update methods.
ii) putting [System.Serializable] above the class definition for all classes in this hierarchy in an attempt to force it to appear in the editor. This would mean I’d have to manually drag the script onto every object in the editor, but at this point I’m just trying to get it to work at all. However, the protected variable is never appearing in the editor.
I’m very new to the Unity environment and I suspect there’s something wrong with my understanding of how to componentise my code. Any help much appreciated!