Making an array that accepts only a string and instances of a class?

4 days ago 11
ARTICLE AD BOX

I have a completely functional system for dialogue in Unity, which uses strings for the text and commands for additional functionality (example: making a sound). Each command is attached to a line, but not all lines have a command, and some have multiple commands. All commands inherit from an abstract class DialogueCommand.

What I'm currently doing is creating an object array and just put a string and then any commands I want like this:

return new object[] { "this is an example line with two commands!", new SetImage("Image3"), new PlayMusic(musicClipsContainer.exampleClip2) "line without commands" "", new SetSmooth(false), "and that's how the lines are made!" new StopMusic() };

This later gets processed to return a struct for each line with its commands.

The thing is: object[] allows me to enter basically anything, while I only want strings and DialogueCommands, which could create errors and confusion if another person wants to use this. So, I want to know if there is a way to make an array that accepts only these data types or any alternative.

Ofc, I have considered other options, like:

Creating an array of the struct that these get converted to. Problem: Too long of a syntax for each line (new DialogueLine("example text", new ExampleCommand()).

Dictionary or list: Also makes syntax longer and more complicated, as if I had for example a List<(string, DialogueCommand[])>. I would have to initialize the DialogueCommand array for each line.

Using interfaces: I could create an array with an interface that is implemented by both data types, but I don't think I can implement an interface in a string.

Is there any way I can exclude anything that isn't a string or DialogueCommand from this array?

Read Entire Article