简体   繁体   中英

How to create correct script which instantiating objects using factory-pattern

I'm creating game. There are coins which player should collect. Now I'm trying to type factory-pattern and I have 2 problems.

In the factory I need to Instantiate prefab of coin and at the same time the factory must be available from other classes. It's unlikely to get factory by its instance, so it must be static. But in this case factory can't hold link to prefab. I thought about implementing singleton already, but in this way I should hold this script on the scene and it's look like some kind of "dirty way".

Coin.cs

public class Coin : MonoBehaviour
{
    CellCoordinates coords;
    public CellCoordinates Coords
    {
        get { return coords; }
        set
        {
            coords = value;
            transform.localPosition = coords.ToWorld();
        }
    }
    static public event System.Action OnCollect;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            Destroy(gameObject, 0.2f);
            OnCollect?.Invoke();
        }
    }
}

CoinFactory.cs

public class CoinFactory : MonoBehaviour
{
    [SerializeField]Coin coinPrefab;
    public Coin Create(Maze.CellCoordinates coords)
    {
        Coin coin = Instantiate(coinPrefab) as Coin;
        coin.Coords = coords;
        return coin;
    }
}

What I would do:

public class CoinFactory : MonoBehaviour
{
    private static CoinFactory instance;

    [SerializeField] private Coin coinPrefab;

    private void Awake()
    {
        instance = this;
    }

    public static Coin Create(Maze.CellCoordinates coords)
    {
        var coin = Instantiate(instance.coinPrefab);
        coin.Coords = coords;
        return coin;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM