Frage

I have an interface which all my monsters should implement.

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

Then I have a concrete monster class (I will add more):

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;
    }

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

}

And a factory class that will produce my monsters:

class MonsterFactory : MonoBehaviour
    {

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

This works but I read that I should not use new and I should use AddComponent. So I tried something like:

class MonsterFactory : MonoBehaviour
    {
        public static GameObject mymonster;            //@first
        public static IMonster getMonster()
        {   
            return mymonster.AddComponent<Monster2>(); //@second                
        }
    }

The problem is that now when I am trying to run the game there is a an error NullReferenceException: Object reference not set to an instance of an object

IMonster monster = MonsterFactory.getMonster();
War es hilfreich?

Lösung

As David said mymonster needs to be initialised. But even then you will run into trouble, as there is one GameObject containing a bunch of Monster2 components.

So instead I suggest:

GameObject go = new GameObject (GameObjectName);
return go.AddComponent<Monster2>();

Now every new monster has its own GameObject and thus can move indepently.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top