2017-06-01 43 views
0

我沒看到這段代碼有什麼問題。它表示變量projectileEnemy沒有分配給任何東西,即使我要通過檢查器窗口分配給它預製件,但檢查器窗口不會更新,因爲有錯誤。我沒有看到腳本實例化預製有什麼問題

using System.Collections; 
    using System.Collections.Generic; 
    using UnityEngine; 

    public class Attack : MonoBehaviour { 
     public Transform playerPos = null; 
     private float playerDist; 
     public GameObject projectileEnemy = null; 

     private void Shoot() 
     { 
      GameObject projectileEnemy = Instantiate(projectileEnemy, transform.position, Quaternion.identity) as GameObject; 
     } 




     void Update() { 
      playerDist = playerPos.position.x - transform.position.x; 

      if (playerDist <= (3) && playerDist >= (-3)) 

      { 
       Shoot(); 

       if (playerDist < (0)) 
       { 
        projectileEnemy.GetComponent<Rigidbody>().AddForce(transform.left * 10); 
       } 
       else 
       { 
        projectileEnemy.GetComponent<Rigidbody>().AddForce(transform.right * 10); 
       } 
      } 

     } 
    } 

回答

4

您必須創建(克隆)彈丸,並使用從(預製)進行復制的一個

// Assin in the inspector the prefab of the projectile 
public GameObject projectileEnemyPrefab ; 

private GameObject projectileClone ; 

private void Shoot() 
{ 
    // Clone the prefab to create the real projectile of the enemy which will be propelled 
    projectileClone = Instantiate(projectileEnemyPrefab , transform.position, Quaternion.identity) as GameObject; 
} 

void Update() { 
    playerDist = playerPos.position.x - transform.position.x; 

    if (playerDist <= (3) && playerDist >= (-3)) 

    { 
     Shoot(); 

     if (playerDist < (0)) 
     { 

      // Propel the instantiated **clone** 
      projectileClone .GetComponent<Rigidbody>().AddForce(transform.left * 10); 
     } 
     else 
     { 
      // Propel the instantiated **clone** 
      projectileClone .GetComponent<Rigidbody>().AddForce(transform.right * 10); 
     } 
    } 

} 
區分