Search code examples
unity-game-engineunity3d-editor

Is there a way to have a script reference an object as a field?


I've had trouble searching around and may be critically misunderstanding how Unity wants you to structure your project, but here is my situation:

I have characters in my game and would like to configure them in the editor. I have made classes that represent different behavior types and actions that can be performed. Is there a way for me to make a field on a script typed for these classes so that I can drag and drop using the inspector to configure different prefabs?

Here is some code demonstrating the situation:

Unit.cs

// A unit on the board.
public class Unit : MonoBehaviour
{
    public UnitAction action;
}

UnitAction.cs

// A unit on the board.
public class UnitAction : MonoBehaviour
{
    // Does things
}

These fields show up in the inspector once this script is applied to a prefab, but there are no options to populate the default field value. If I make the field type UnityEngine.Object, I can put the scripts there, but that seems like something I do not want.


Solution

  • It sounds like you are trying to serialize references to scripts themselves instead of instances of those scripts. There are a couple of ways that you may want to do this:

    1. You could attach your UnitAction scripts as components of a GameObject that is in a context accessible to your "Unit" object (in the same scene, a child of the "Unit" object, or - probably the most common case - the "Unit" object itself). Then you will be able to serialize those instantiated components into the fields in your Unit class. This is the most common use case.

    2. You could create a prefab for each of your UnitAction components and then serialize those prefabs into your Unit class fields. You would then instantiate a UnitAction at runtime. This doesn't really seem appropriate for your case based on what you described because a UnitAction probably isn't something that needs to be dynamically instantiated, but it is important to be aware of. This article has an example of using this method for giving a unit a list of spells (and also provides some good context on how to think about using unity components that would probably be valuable to you):

    Unity: Now You're Thinking With Components