首页 > 解决方案 > 找不到类型或命名空间名称“player”。(您是否缺少指令或程序集参考)

问题描述

我正在统一制作一个播放器脚本以显示它的健康和功率水平。虽然我得到了所需的输出,但有人可以解释上述问题是什么。这是代码:-

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();

真的是很严重的事情,需要看看。我也尝试过以其他方式调用该函数,但这仅符合我的愿望。我试图在谷歌上找到一些东西,但找不到准确的答案

标签: c#unity3d

解决方案


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

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根本不是一回事!


推荐阅读