Unity で初めてのゲームを開発しており、Abstract Factory
パターンを適用してゲームのモンスターを作成しようとしています。すべてのモンスターが実装する必要があるインターフェイスがあります。
interface IMonster
{
void setSpeed(float s);
float getSpeed();
void SetMonsterPosition(Vector2 pos);
Vector2 GetMonsterPosition();
void DestroyMonster();
void MoveMonster();
}
私は具体的なモンスターを持っています
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;
}
....
}
そして、後で具体的な Monster オブジェクトをランダムに作成できるように、新しい Monster オブジェクトを返すメソッドを持つ Factory クラスを作成したいと考えています。私は次のように書いた:
class MonsterFactory
{
public IMonster getMonster()
{
return new Monster2();
}
}
そして、私はこのファクトリーをメインで次のように使用しようとしています:
private IMonster monster;
private MonsterFactory myMonsterFactory;
void Start () {
monster = myMonsterFactory.getMonster();
}
ゲームを実行しようとすると、次のエラーが表示されますNullReferenceException: Object reference not set to an instance of an object
。