首页 > 解决方案 > 如何要求公共变量(预制件)在 UNITY 中具有某个组件(刚体)?

问题描述

我正在尝试实现“Shoot” MonoBehaviour。我希望它做一些非常简单的事情,它应该将预制件作为“输入”(暂时将其存储在“射弹”公共变量中),然后简单地实例化它并向它的 RigidBody 添加一个向前力(相对于它附加到的对象,例如坦克)。

但是,如果我不小心插入了没有 RigidBody 的 Prefab,我不希望我的游戏崩溃。(事实上​​,如果它甚至不允许我添加没有 RigidBody 的 Prefab 作为射弹,那就太好了)。

我试过使用“RequireComponent”属性,但它看起来只适用于类。有什么方法可以做到这一点,而不必在每次我想射击时检查 Projectile 是否有刚体?

我尝试了下面的代码,但它给了我一个错误,说我不能将刚体实例化为游戏对象。这是可以理解的,但我在这里没有想法了。

public class Shoot : MonoBehaviour
{

    public Rigidbody projectile;
    public float firePower = 5f;

    public void Fire()
    {
        GameObject projectileInstance = Instantiate(projectile) as GameObject;
        //maybe add some particles/smoke effect
        projectile.GetComponent<Rigidbody>().AddForce(firePower * transform.forward);
    }
}

标签: unity3dcomponentsinstantiationgameobject

解决方案


您可以在运行时添加所需的组件,例如:

    // First check if there is no rigidbody component on the object
    if (!currentPrefab.GetComponent<Rigidbody>()){
        // Add the Rigidbody component
        currentPrefab.AddComponent<Rigidbody>();

        // You can also add a collider here if you want collisions
        var bc = currentPrefab.AddComponent<BoxCollider>();

        // And you'll have to calculate the new collider's bounds
        Renderer[] r = t.GetComponentsInChildren<Renderer>();
        for(var i=0; i<r.length; i++) {
            bc.bounds.Encapsulate(r[i].bounds);
        }
    }

推荐阅读