2017-07-21 33 views
0

我將殭屍預製件附加到殭屍對象;然而,當我按下Play時,腳本會在殭屍對象上消失。我按Play時如何確保腳本保留在對象上?統一:當進入播放模式時,對象上的腳本消失

我宣佈我的變量並初始化它。我知道這是基本的東西,但您的幫助將不勝感激!

public class PlayerLifeCollider : MonoBehaviour { 

    public Zombie zombie; //declared 
    public float damage = 1; 

    public void Start() 
    { 
     zombie = GetComponent<Zombie>(); //instantiated 
    } 

    private void Update() 
    { 
     zombie.DamagePlayer(damage); //**Null error here** 
    } 
} 

public class Zombie : MonoBehaviour 
{ 
    public int currentHealth; 
    private Player player; 
    private PlayerLifeCollider playerCollider; 
    public int damage; 

    public void Start() 
    { 
     playerCollider = GetComponent<PlayerLifeCollider>(); 
    } 

    public void Damage(int damageAmount) 
    { 
     currentHealth -= damageAmount; 
     if (currentHealth <= 0) 
     { 
      playerCollider.ObjectsInRange.Remove(gameObject); 
      gameObject.SetActive(false); 
     } 

    } 

    public void DamagePlayer(float damage) 
    { 
     player.Life(damage); 
    } 
} 

public class Player : MonoBehaviour { 

public float playerLife = 100; 

public void Life (float damage) 
    { 
     playerLife -= damage; 
     if (playerLife <=0) 
     { 
      playerLife = 100; 
      SceneManager.LoadScene(2); 
     } 
} 

Before Zombie Attached

After Zombie Not Attached

+0

'player.Life(float)'的實現是什麼? –

+0

如果在檢查器中已經分配了'zombie = GetComponent ()',則不需要指定'zombie = GetComponent ()'。 – ryeMoss

回答

1

這裏的問題是,您在運行時覆蓋了zombie的值,導致它被替換爲空值。代碼:

public void Start() 
{ 
    zombie = GetComponent<Zombie>(); //instantiated 
} 

嘗試檢索從父遊戲物體(PlayerLifeCollider)一Zombie腳本組件 - 但沒有一個Zombie腳本上PlayerLifeCollider!所以它返回null並將其分配給變量zombie

因爲您已經通過將其拖動到檢查器中的公共變量上而將值分配給zombie,所以您無需在運行時爲其分配值。您可以安全地刪除此行,並保留該值。

希望這會有所幫助!如果您有任何問題,請告訴我。

+0

你怎麼知道什麼時候通過拖動或通過GetComponent爲一個對象分配一個值()? – MrHero

+0

@MrHero最簡單的做法是創建一個變量public並將值拖到它上面,因爲您不需要通過腳本獲取它所在的對象的引用(所以您可以調用'GetComponent()')。但是當你需要從運行時創建的對象(例如,通過實例化的預製)中檢索腳本時,你不能事先將它們拖到變量上(因爲它們不存在),所以你需要用'GetComponent ()'。在運行時執行它也會使腳本更容易在場景中重用,因爲每次添加時都不需要將對象拖動到其變量上。 – Serlite

相關問題