找不到类型或命名空间名称"player".(您是否缺少指令或程序集引用)



我在unity中制作一个玩家脚本来显示它的生命值和能量水平。虽然我得到了想要的输出,但有人能解释一下上面的问题是关于什么的吗?代码如下:-

int health = 100;
int power = 0;
string name = Console.Readline("Hey player!! please type in your name. (Kindly do not use your real name)");

public Player()
{
Debug.Log("health is " + health);
Debug.Log("power level is " + power);
Debug.Log("the name of the player is " + name);
}

,函数在这里:-

Player Warrior = new Player();
这真的是一件严重的事情吗?我也尝试过以其他方式调用函数,但这只符合我的愿望。我试着在谷歌上找一些东西,但找不到准确的答案

您所编写的脚本是一个构造函数:

public Player()
{
Debug.Log("health is " + health);
Debug.Log("power level is " + power);
Debug.Log("the name of the player is " + name);
}

构造函数是唯一可以声明没有返回类型的方法(因为它们总是用new关键字调用,系统会为你返回新的实例)。

并且构造函数只能在与方法本身同名的类中创建:

public class Player
{
public Player()
{
...
}
}

所以,要么你的构造函数在它所涉及的类之外,要么你忘记添加返回类型:void根本不是一回事!