How can I pull a string from a separate class while keeping the class in a list in my main (C#, Unity)

Viewed 42

I feel like I should preface this by saying, I am still a beginner and knowing me, I could very well be forgetting something that is ridiculously simple and over complicating in the process. But nonetheless, I have been unable to figure this out.

I’m trying to create a dialogue system in unity that displays a string of text as well as a sprite. However, I am not sure how to pull the string from a separate class while also ensuring that I can keep the class in a list so I can cycle through the text and sprite together. Currently the class I'm attempting to pull from looks like this:

public class DialogueInfo
{
    public Sprite emotion;
    public string Words;
}

The list looks like this:

public List<DialogueInfo> dialogueInfo = new List<DialogueInfo>();

And I'm trying to use the "Words" string here:

NPC.dialogLines = dialogueInfo.Words;

This however, does not work. I am getting an error saying that "'List<dialogueHolder.DialogueInfo>' does not contain a definition for 'Words' and no accessible extension method..." Any suggestions? This whole process could be a very bad way of doing things and if so, suggestions would be appreciated. If more context is needed, I will gladly provide it.

Note: by using a list i am just trying to keep a format that looks like this: Unity's formatting of a list/array but with both text and a sprite in a single element If I have to use a different approach then that is alright.

1 Answers

Your variable name dialogInfo is misleading. It's not a dialogInfo, it's a box (a list) where there is a lot of dialogInfo inside.

Let's call it dialogInfoList instead.

public List<DialogueInfo> dialogueInfoList = new List<DialogueInfo>();

Extract all the words

If you want to get all the "Words" properties of all the element, you can use linq for this:

NPC.dialogLines = dialogueInfoList.Select(dialogInfo => dialogInfo.Words);

Depending on the type of NPC.dialogueLines (List for instance), you may want to add .ToList() after the Select().

Simpler: just link all the original list

You mentioned you might miss something simpler.

It really depends on what you want to achieve, the quesiton is not very clear about that, but what about keeping all the "DialogInfo" list with the NPC object instead?

Something like:

NPC.DialogueInfoList = dialogueInfoList;

With DialogueInfoList being a property / field of type List<DialogueInfo>

Related