mardi 30 novembre 2021

Implementing Factory Method design pattern in Unity

i have the following code:

Product code -

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

public abstract class Guns : MonoBehaviour //product
{
    public abstract void shoot();
    public GameObject CreateBullet(GameObject bullet)
    {
        return Instantiate(bullet, transform.position, Quaternion.identity);
    }
    public void ShootBullet(GameObject bullet, Vector3 direction)
    {
        bullet.transform.Translate(direction * Time.deltaTime);
    }

}

Concrete Product Code 1

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

public class M16 : Guns //ConcreteProduct
{
    [SerializeField] GameObject m16bullet;
    Vector3 m16bulletdirection = new Vector3(5, 0, 0);

    public override void shoot()
    {
        CreateBullet(m16bullet);
        ShootBullet(m16bullet, m16bulletdirection);
    }

}

Concrete Product Code 2

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

public class Uzi : Guns //ConcreteProduct
{
    [SerializeField] GameObject uzibullet;
    Vector3 uzibulletdirection = new Vector3(10, 0, 0);

    public override void shoot()
    {
        CreateBullet(uzibullet);
        ShootBullet(uzibullet, uzibulletdirection);
    }
}

Creator Code

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

public abstract class GunCreator : MonoBehaviour //Creator
{
    public abstract Guns GunFactory();
}

Concrete Creator Code 1

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

public class M16Creator : GunCreator // ConcreteCreator
{

    public override Guns GunFactory()
    {
        return new M16();
    }
}

Concrete Creator Code 2

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

public class UziCreator : GunCreator // ConcreteCreator
{
    public override Guns GunFactory()
    {
        return new Uzi();
    }
}

and a client code, which currently do nothing as I dont know how to make a gun using this method. So How do all of this help me create new gun prefab with the relevant code on them?

Besides, as far as i understand, every new gun will have to have a NewGunCreator class that derives from GunCreator and a NewGun class that derives from Guns. wouldnt it be easier to leave out the creator classes?

cheers!

Aucun commentaire:

Enregistrer un commentaire