如何统一实现Null对象?

时间:2017-02-05 21:51:17

标签: c# unity3d

我关注如何做空对象的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.

1 个答案:

答案 0 :(得分:1)

如何使用单个静态空对象?

private static ChessPiece nullInstance;

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

    return nullInstance;
}