我正在尝试基于当前场景的索引读取不同的文本文件(使用Unity术语)。因此,我决定使用如下switch语句:
void MyReadString()
{
Scene currentScene = SceneManager.GetActiveScene(); // Unity command to get the current scene info
int buildIndex = currentScene.buildIndex; // Unity command to get the current scene number
string path = string.Empty; // Create an empty string variable to hold the path information of text files
switch (buildIndex)
{
case 0:
string path = "Assets/Scripts/some.txt"; //It says here that the variable path is assigned but never used!
break;
case 1:
string path = "Assets/Scripts/another.txt"; //Same here - assigned but never used.
break;
// and many other cases - atleast 6 more
}
StreamReader reader = new StreamReader(path); // To read the text file
// And further string operations here - such as using a delimiter, finding the number of values in the text etc
}
如果我将这一行注释掉:
string path = string.Empty;
然后
StreamReader reader = new StreamReader(path); // says here the name "path" does not exist in the current context.
我知道这与switch语句的范围有关。但是,将开关外部的字符串变量声明为“空”是行不通的。请让我知道是否可以在Switch语句中分配字符串值并稍后使用该值。或者,如果无法解决,请向我建议解决方法。
答案 0 :(得分:5)
您遇到了问题,因为您要在switch语句中再次重新声明path变量。仅在switch语句外声明一次,然后在switch语句中分配它。
void MyReadString()
{
Scene currentScene = SceneManager.GetActiveScene(); // Unity command to get the current scene info
int buildIndex = currentScene.buildIndex; // Unity command to get the current scene number
string path = null;
// Create an empty string variable to hold the path information of text files
switch (buildIndex)
{
case 0:
path = "Assets/Scripts/some.txt"; //It says here that the variable path is assigned but never used!
break;
case 1:
path = "Assets/Scripts/another.txt"; //Same here - assigned but never used.
break;
// and many other cases - atleast 6 more
}
StreamReader reader = new StreamReader(path); // To read the text file // And further string operations here - such as using a delimiter, finding the number of values in the text etc
}
不相关,但是请注意,这不是不是如何在Unity中读取文件。在构建项目时,该代码将失败。使用Resources API或使用Assetbundles。
答案 1 :(得分:2)
您正试图重新声明一个变量-但实际上您只想为在此处声明的现有变量分配一个新变量:
// This line is still needed, and must be before the switch statement.
// Ideally, remove the initialization - your switch statement should cover
// all cases, I expect.
string path = string.Empty;
所以这个:
case 0:
string path = "Assets/Scripts/some.txt"; //It says here that the variable path is assigned but never used!
break;
case 1:
string path = "Assets/Scripts/another.txt"; //Same here - assigned but never used.
break;
应该是:
case 0:
path = "Assets/Scripts/some.txt";
break;
case 1:
path = "Assets/Scripts/another.txt";
break;
IMO,将这种逻辑放在单独的方法中,或者只是
有一个数组或Dictionary<int, string>
。例如:
string path = GetScriptPath(buildIndex);
或(其中scriptPaths
是string[]
或Dictionary<int, string>
)
string path = scriptPaths[buildIndex];
答案 2 :(得分:1)
您对范围位是正确的。在switch语句中声明的变量路径使其只能从该语句中访问。 为了使您可以从语句外部访问变量,必须在更大的范围内声明它。
如果要访问该变量:
在当前形式下,每次switch语句遇到一个情况时,您都在创建一个新字符串,通过移动声明,您将只分配一个预先声明的字符串。