如何发射类似弹丸的粒子?

时间:2018-08-30 16:24:19

标签: unity3d particles

我制造了一个坦克,可以通过单击鼠标来发射球体。

我的C#脚本:

 GameObject prefab;

 // Use this for initialization
 void Start () {
     prefab = Resources.Load("projectile") as GameObject;
 }

 // Update is called once per frame
 void Update() {
     if (Input.GetMouseButtonDown(0))
     {
         GameObject projectile = Instantiate(prefab) as GameObject;
         projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
         Rigidbody rb = projectile.GetComponent<Rigidbody>();
         rb.velocity = Camera.main.transform.forward * 40;
     }   

 }

在此脚本中,我拍摄了名为projectile的网格。但是我想拍摄一个粒子球而不是一个网格。我已经尝试在脚本上将particle更改为Orbparticle,但是没有生成任何对象。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

没有产生任何对象,因为您可能没有名为function populateSelGrp() { $.get("ajax/activoFijo/populateSelGrp.php", { }, function (data, status) { //load options to dropdown list $(".option_grp").html(data); } ); } function changeGrpId(){ var id_grp = document.getElementById("select_grp").value; populateSelSgrp(id_grp); } function populateSelSgrp(id_grp) { $.ajax({ url: "ajax/activoFijo/populateSelSgrp.php", method: "POST", data:{id_grp: id_grp}, success:function(data){ $(".option_sgrp").html(data); } }) } 的资源。运行脚本时检查是否有任何错误。如果Resources.Load在给定的路径中找不到所需的对象,它将给出Orbparticle,这可能就是为什么没有生成任何对象的原因。

如果要射击粒子而不是网格物体,则需要将null设置为预先准备的具有所需粒子系统的GameObject。我建议不要为此使用Resources.Load。

1。使用Resources.Load。

将您的代码更改为此,以便它在找不到资源时提醒您:

prefab

现在,要使其正常工作,您需要一个名为“ OrbParticle”的预制件或将变量GameObject prefab; // Use this for initialization void Start () { string name = "OrbParticle"; prefab = Resources.Load<GameObject>(name); if (prefab == null) { Debug.Error("Resource with name " + name + " could not be found!"); } } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { GameObject projectile = Instantiate(prefab) as GameObject; projectile.transform.position = transform.position + Camera.main.transform.forward * 2; Rigidbody rb = projectile.GetComponent<Rigidbody>(); rb.velocity = Camera.main.transform.forward * 40; } } 设置为任何字符串。 Resources.Load在诸如name之类的路径中查找项目。因此,您必须在该Resources文件夹中拥有“ OrbParticle”预制件。除非您有使用Resource.Load的特定原因,否则我强烈建议您使用解决方案2。

2。抛弃资源。直接加载并使用预制件。

将代码更改为此:

Assets/Resources

然后执行以下操作:

  1. 创建一个新的空GameObject。
  2. 将粒子系统附加到游戏对象。
  3. 制作新的预制资产。
  4. 将新创建的GameObject拖放到Prefab资产中。
  5. 将预制件拖放到Monobehaviour(进行射击的对象)的public GameObject prefab; // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { GameObject projectile = Instantiate(prefab) as GameObject; projectile.transform.position = transform.position + Camera.main.transform.forward * 2; Rigidbody rb = projectile.GetComponent<Rigidbody>(); rb.velocity = Camera.main.transform.forward * 40; } } 字段中。它将在检查器中具有一个预制件字段。这就是为什么我们将prefab设置为公共字段的原因)。

如果仍然遇到问题,请查看Unity的层次结构以查看是否根本没有创建任何对象。可能是实例化一个GameObject的情况,但由于某种原因该GameObject是不可见的,或者没有实例化在您期望的位置。

相关问题