如何拍射像弹丸一样的粒子?

问题描述 投票:0回答:1

我做了一个坦克,点击鼠标射击球形球。

我的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,但没有生成任何对象。我做错了什么?

unity3d particles
1个回答
1
投票

没有生成对象,因为您可能没有名为Orbparticle的资源。运行脚本时检查是否有任何错误。如果Resources.Load没有通过你给它的路径找到你想要的对象,那么它将给出null,这可能就是为什么没有对象产生的原因。

如果你想拍摄粒子而不是网格,那么你需要做的是将prefab设置为你预先准备好的粒子系统所需的GameObject。我建议不要使用Resources.Load。

1. Using Resources.Load.

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

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;
    }   
}

现在为了使其工作,您需要一个名为“OrbParticle”的预制件或您将变量name设置为的任何字符串。 Resources.Load在路径中查找项目,例如Assets/Resources。所以你必须在Resources文件夹中找到你的“OrbParticle”预制件。除非您有使用Resources.Load的特定原因,否则我强烈建议您使用解决方案2。

2. Ditching Resources.Load and using the Prefab directly.

将您的代码更改为:

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;
    }   
}

然后这样做:

  1. 创建一个新的空GameObject。
  2. 将ParticleSystem附加到GameObject。
  3. 制作一个新的预制资产。
  4. 将新创建的GameObject拖放到Prefab资产中。
  5. 将预制件拖放到Monobehaviour中的prefab区域(进行射击的对象。它将在Inspector中有一个预制区域。这就是我们将prefab设置为公共区域的原因)。

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

© www.soinside.com 2019 - 2024. All rights reserved.