Question

I am developing my first game in Unity and I am trying to apply the Abstract Factory pattern to create the Monsters of the game. I have an Interface that all Monsters should implement:

interface IMonster
    {
        void setSpeed(float s);
        float getSpeed();
        void SetMonsterPosition(Vector2 pos);
        Vector2 GetMonsterPosition();
        void DestroyMonster();
        void MoveMonster();
    }

I have a concrete Monster

public class Monster2 : MonoBehaviour, IMonster
{

    ....

    public Monster2()
    {
        speed = Random.Range(0.05f, 0.15f);
        monster = (GameObject)Instantiate(Resources.Load("Monster2"));
        float height = Random.Range(0, Screen.height);
        Vector2 MonsterStartingPosition = new Vector2(Screen.width, height);
        MonsterStartingPosition = Camera.main.ScreenToWorldPoint(MonsterStartingPosition);
        monster.transform.position = MonsterStartingPosition;
    }

    ....

}

And I want to create a Factory class that has a method which returns a new Monster object so I will be able later to create concrete Monster objects randomly. I wrote the following:

 class MonsterFactory
    {

        public IMonster getMonster()
        {
            return new Monster2();
        }
    }

And I am trying to use this Factory in my main like this:

 private IMonster monster;
    private MonsterFactory myMonsterFactory;

    void Start () {
        monster = myMonsterFactory.getMonster();
    }

When I am trying to run the game I get the following error NullReferenceException: Object reference not set to an instance of an object Any idea what I am doing wrong?

Was it helpful?

Solution

Change GetMonster method in the MonsterFactory class to be static

class MonsterFactory
{
    public static IMonster GetMonster()
    {
        return new Monster2();
    }
}

In your Main method call it

private IMonster monster;

void Start() 
{
    monster = MonsterFactory.GetMonster();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top