user
user

Reputation: 3199

How to implement Null Object in unity?

I was following this example on how to do null objects. This is how far I got, before I got stuck.

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>() this part is throwing me off. Since there is nothing in the example about something like that in the article.

It is working, the only problem is that I keep getting many instances of NullChessPiece.

//See comments for more info.

Upvotes: 2

Views: 130

Answers (1)

ymz
ymz

Reputation: 6924

how about using a single static null object?

private static ChessPiece nullInstance;

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

    return nullInstance;
}

Upvotes: 1

Related Questions