繁体   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