【问题标题】:Field 'XXX.AppMain.p1' is Never Assigned to, And Will Always Have Its Default Value Null字段“XXX.AppMain.p1”从未分配给,并且始终具有其默认值 Null
【发布时间】:2014-11-26 16:41:47
【问题描述】:

当我明确为 p1 赋值时,我不明白为什么会收到此错误消息,您可以在以下代码中看到:

public class AppMain
{
    private static GraphicsContext graphics;
    private static bool running;
    private static Sprite bckgnd1, bckgnd2;
    private static Sprite openScreen, instructScreen, gameOverScreen;
    private static Vector3 pos1, pos2, pos3, pos4, pos5;
    private static Player p1, p2;
    private static Fruit apple, orange, banana;
    private static Stopwatch clock;
    private static long startTime, stopTime, deltaT;
    private static Random rand;
    enum GameState {
        opening,
        instructions,
        play,
        gameOver};
    private static GameState currentState;
    private static List<Player> pList;


    public static void Main (string[] args)
    {
        Initialize ();

        while (running == true) {
            startTime = clock.ElapsedMilliseconds;
            SystemEvents.CheckEvents ();
            Update ();
            Render ();
            stopTime = clock.ElapsedMilliseconds;
            deltaT = stopTime - startTime;
        }
    }

    public static void Initialize ()
    {
        running = true;

        pList = new List<Player>();

        graphics = new GraphicsContext ();

        Texture2D pTex1 = new Texture2D("/Application/Assets/macmuffin.png", false);
        Texture2D pTex2 = new Texture2D("/Application/Assets/macmuffin1.png", false);

        pos1 = new Vector3(200, 600, 0);
        pos2 = new Vector3(400, 600, 0);

        Player p1 = new Player(pTex1, pos1, 1, graphics, "Player 1");
        Player p2 = new Player(pTex2, pos2, 2, graphics, "Player 2");
        pList.Add (p1);
        pList.Add (p2);
    }

另外,如果你能告诉我为什么当我尝试渲染玩家时,错误消息“未处理的异常:System.NullReferenceException:对象引用未设置为 Cain_Game3.AppMain.Main 的对象实例(系统.String[] args) [0x00000] in :0" 出现。谢谢。

【问题讨论】:

  • 您有一个p1 变量和一个p1 字段。该字段未分配给。

标签: c# list null field assign


【解决方案1】:

您正在声明一个新的、本地范围的 p1,而不是分配给靠近顶部的 p1 成员声明。

你可能想改变这个:

  Player p1 = new Player(pTex1, pos1, 1, graphics, "Player 1");

到这里:

  p1 = new Player(pTex1, pos1, 1, graphics, "Player 1");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多