无法将类型"System.Collections.Generic.List"隐式转换为<string>"字符串"


using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class TextChange : MonoBehaviour
{
public List<string> ingr = new List<string>();
void Start()
{
ingr.Add("Ingredients:");
}
void Update()
{
GetComponent<TextMesh>().text = ingr;
}
void Lemon()
{
ingr.Add("Lemon");
}
void Water()
{
ingr.Add("Water");
}
}

我唯一一次提到字符串是在创建列表时,但在运行时会出现此错误。我是C#的新手。

检查这个:

void Update()
{
StringBuilder build = new StringBuilder();
foreach (string item in ingr)
{
build.Append(item);
build.Append(Environment.NewLine);
}
GetComponent<TextMesh>().text = build.ToString();
}

不能将列表放入字符串中。。。

字符串基本上只是一些文本。GetComponent<TextMesh>().text是TextMesh应该显示的文本,因此它是一个字符串。在Update函数中,您试图将此字符串设置为等于ingr。

然后它告诉你的问题是,ingr不是一个字符串,而是一个字符串列表——它不能将一个字符串设置为等于多个字符串。

有一件事不会出错,那就是GetComponent<TextMesh>().text = ingr[0];在这里,您将TextMesh的文本设置为列表中的第一个条目,该条目似乎是";配料:"。

不过,我猜你想要的是,它也显示ingr中的所有其他条目,每个条目都在自己的行上。实现这一点的一种方法是将ingr作为字符串,而不是字符串列表。然后执行:ingr += "n Lemon";,而不是例如ingr.Add("Lemon")

这种方法将使您的代码:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class TextChange : MonoBehaviour
{
public string ingr = "";
void Start()
{
ingr += "Ingredients:";
}
void Update()
{
GetComponent<TextMesh>().text = ingr;
}
void Lemon()
{
ingr += "Lemon";
}
void Water()
{
ingr += "Water");
}
}

您当前正在将"文本字符串"设置为"字符串列表"。要解决此问题,您可以选择

用字符串替换列表:

public string ingr = "Ingredients:n";
void Update() {
GetComponent<TextMesh>().text = ingr;
}
void AddIngredientToList(string ingredient) {
ingr += ingredient + "n";
}

或者,您可以将列表中的每个元素添加到一个字符串中。

将列表加入字符串:

public List<string> ingr = new List<string>();
void Start() {
ingr.Add("Ingredients:");
}
void Update() {
GetComponent<TextMesh>().text = string.Join(",", ingr)
}
void AddIngredientToList(string ingredient) {
ingr.Add(ingredient);
}

最新更新