【问题标题】:The type or namespace name ‘player’ could not be found. (Are you missing a directive or an assembly reference)找不到类型或命名空间名称“player”。 (您是否缺少指令或程序集参考)
【发布时间】:2021-11-16 15:38:41
【问题描述】:

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

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 class Player { ... } 里面吗?同样对于 Unity 特定的 .. 你不想拥有 Console.ReadLine ...

标签: c# unity3d


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2012-05-01
    相关资源
    最近更新 更多