gpt4 book ai didi

c# - 如何统一实现空对象?

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:52 26 4
gpt4 key购买 nike

我正在关注 this有关如何处理空对象的示例。这是我在遇到困难之前的进展情况。

棋子.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

典当.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

棋盘管理器.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.

最佳答案

使用单个静态空对象怎么样?

private static ChessPiece nullInstance;

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

return nullInstance;
}

关于c# - 如何统一实现空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com