我正在遵循this示例,了解如何执行空对象。这就是我被困住之前走了多远。

ChessPiece.cs

using System.Collections;
using UnityEngine;

public abstract class ChessPiece: MonoBehaviour
{
    public int CurrentX{ set; get; }
    public int CurrentZ{ set; get; }

    public virtual bool[,] PossibleMove()
    {
        return new bool[8, 8];
    }

    public virtual bool isNull
    {
        get{ return false; }
    }

    public static ChessPiece NewNull()
    {
        return new GameObject("NullChessPiece").AddComponent<NullChessPiece>();
    }
}
// same file
public class NullChessPiece: ChessPiece
{
    public override bool isNull
    {
        get{ return true; }
    }
}


Usage

Pawn.cs

using System.Collections;
using UnityEngine;

public class Pawn: ChessPiece
{
    public override bool[,] PossibleMove()
    {
        bool[,] result = new bool[8,8];
        // Usage
        if(!piece(0, 1).isNull) {
            result[CurrentX, CurrentZ + 2] = true;
        }

        return result;
    }

    // Each time this function is executed I get NullChessPiece objects
    // in my Hierarchy pane and they just keep on adding
    // how do I stop this?
    private ChessPiece piece(int x, int z)
    {
        return BoardManager.Instance.ChessPieces[CurrentX + x, CurrentZ + z] ??
               ChessPiece.NewNull();
    }
}


Just in case you need to see what's going on here

BoardManager.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BoardManager: MonoBehaviour
{
    public static BoardManager Instance{ set; get; }
    public ChessPiece[,] ChessPieces{ set; get; }

    private void Start()
    {
        Instance = this;
    }
}


GameObject("NullChessPiece").AddComponent<NullChessPiece>()这部分让我失望。由于示例中没有涉及本文中类似内容的内容。

它正在工作,唯一的问题是我不断获得许多NullChessPiece实例。

//See comments for more info.

最佳答案

如何使用单个静态null对象呢?

private static ChessPiece nullInstance;

public static ChessPiece NewNull()
{
    if (nullInstance == null)
    {
        nullInstance = new GameObject("NullChessPiece").AddComponent<NullChessPiece>();
    }

    return nullInstance;
}

10-06 11:56