You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity报错CS0103:使用String.Join拼接列表字符串失败求助

解决Unity中String不存在的编译错误

嘿,别担心,这个问题其实很常见,尤其是刚接触C#和Unity的时候!

错误原因

你遇到的CS0103: The name 'String' does not exist in the current context错误,本质是因为String类属于.NET的System命名空间,但你的代码里没有导入这个命名空间,所以编译器找不到它。

两种快速解决方案

方案1:直接使用小写的string(推荐)

在C#中,string是System.String的内置别名,Unity默认已经支持这个别名,不需要额外导入命名空间。你只需要把代码里的String.Join改成string.Join即可:

修改后的关键代码片段:

Debug.Log(string.Join(", ", DeadNumbers));
DeadNumbers_str = string.Join(",", DeadNumbers);
Debug.Log(DeadNumbers_str);

方案2:导入System命名空间

如果你习惯使用大写的String,可以在代码顶部的引用列表中添加using System;:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

这样编译器就能识别String类了。

修改后的完整代码示例

这里是调整后的完整代码,你可以直接替换测试:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Random_Number : MonoBehaviour {
    public List <int> ListofNumbers = new List<int>(); // List of the numbers being called
    public List <string> DeadNumbers = new List<string>(); // List of numbers that have been called
    public Text text_to_be_Printed; // Text Element
    private int numberSelected;
    private string numberSelected_str;
    public string DeadNumbers_str;

    void Start() {
        text_to_be_Printed = GetComponent<Text>();
        for(int i = 1; i <= 90; i++){
            ListofNumbers.Add(i); // Makes a list of all the numbers
        }
    }

    void Update() {
        if (Input.GetKeyDown("space")){ // If space is pressed -text
            numberSelected = ListofNumbers[Random.Range (0, ListofNumbers.Count)]; // Get a random number text
            numberSelected_str = numberSelected.ToString();
            text_to_be_Printed.text = numberSelected_str;
            DeadNumbers.Add(numberSelected_str);
            ListofNumbers.Remove(numberSelected);
            
            // 这里已经可以正常运行了
            DeadNumbers_str = string.Join(", ", DeadNumbers);
            Debug.Log(DeadNumbers_str);
        }
    }
}

额外小提示

  • 以后遇到类似“某某类不存在”的错误,首先检查对应的命名空间是否已经导入。
  • 对于C#的基础类型,比如string、int、bool,直接用小写的别名更符合常规写法,也能避免这类命名空间问题。

内容的提问来源于stack exchange,提问作者Jack Godfrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:56:07