2014-03-04 24 views
0

我有一個我所有怪物應該實現的接口。在團結中使用addComponent而不是新關鍵字

namespace Assets.Scripts 
{ 
    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; 
    } 

    void Start() 
    { 

    } 

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

    } 

} 

而一個工廠類,將產生我的怪物:

class MonsterFactory : MonoBehaviour 
    { 

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

這工作,但我讀我不應該使用新的,我應該使用AddComponent。所以,我想是這樣的:

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

的問題是,現在當我試圖運行遊戲有一個錯誤NullReferenceException: Object reference not set to an instance of an object

IMonster monster = MonsterFactory.getMonster(); 

回答

3

正如大衛說被初始化mymonster需求。但即使如此,你也會遇到麻煩,因爲有一個GameObject包含一堆Monster2組件。

所以不是我建議:

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

現在每一個新的怪物都有自己的遊戲對象,因此可以自主承擔移動。

相關問題