簡體   English   中英

Unity3D:如何調用從另一個類實例化預制件的方法?

[英]Unity3D: How to call a method that instantiates a prefab from another class?

我有一個名為Player的游戲對象,並且附加了兩個腳本。 Player腳本正在偵聽輸入,並從第二個名為LaserController的腳本中調用一個方法。

第二個腳本負責實例化具有LineRenderer組件的預制件,並控制繪制線條的方式及其生命周期。 該預制件已附加到該腳本的層次結構上。

如果將這些腳本合並為一個類,則不會有問題。 但是我使用它們的方式導致此錯誤:

NullReferenceException: Object reference not set to an instance of an object

玩家等級

 public class Player : MonoBehaviour
 {
     LaserController laserController;

     void Update()
     {
         if (Input.GetMouseButton(0))
         {
             laserController.ShootLaserBeam(Input.mousePosition); // NullReferenceException is thrown 
         }
         if (Input.GetMouseButtonUp(0))
         {
             laserController.RemoveLaserBeam();
         }
     }
 }

激光控制器類

 public class LaserController : MonoBehaviour
 {
     public GameObject laserPrefab;
     public GameObject laserInstance;

     public LineRenderer lineRenderer;
     public EdgeCollider2D edgeCollider;

     protected bool isBeamActive;

     public void ShootLaserBeam(Vector3 mousePosition)
     {
         if (isBeamActive == false)
         {
             CreateLaser(mousePosition);
         }
     }

     public void RemoveLaserBeam()
     {
         Destroy(edgeCollider);
         Destroy(laserInstance);
         isBeamActive = false;
     }

     private void CreateLaser(Vector3 mousePosition)
     {
         float turretY = transform.position.y;
         Vector2 turret = new Vector2(0, turretY);
         laserInstance = Instantiate(laserPrefab, Vector3.zero, Quaternion.identity);
         lineRenderer = laserInstance.GetComponent<LineRenderer>();
         edgeCollider = laserInstance.GetComponent<EdgeCollider2D>();

         isBeamActive = true;
         // do bunch of other things with the lineRenderer and Collider....
     }
 }

如果Controller腳本已附加到另一個對象,那么我會明白為什么存在引用錯誤,但是兩個腳本都附加到了同一對象。 如果有人可以指出我在這里缺少的內容,我將不勝感激。

只是一個猜測,但是laserController本身為空。 由於兩個腳本都在同一個游戲對象上,因此可以使用GetComponent對其進行定義。

嘗試改變

LaserController laserController;

LaserController laserController= this.GetComponent<LaserController>();

如果您有兩個游戲對象,一個用於Player,一個用於LaserController,那么您也可以取消將lasercontroller變量公開,並通過將游戲對象拖到Unity中的變量來對其進行定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM