unity3d - 如何要求公共变量(预制件)在 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);
}
}
解决方案
您可以在运行时添加所需的组件,例如:
// 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);
}
}
推荐阅读
- video - 在 Node.js (Express.js) 专用服务器上托管和交付视频
- html - 按下按钮后在exist-db中执行xquery函数
- python-3.x - 如何修复 AWSIoTPythonSdk.exception.AWSIoTException.subscribeTimeoutException
- python-3.x - 熊猫中是否有任何软件包可以根据其他列计算列的选定部分值的平均值
- swift - Swift KVO 绑定未更新
- centos7 - 无法启动 OpenLDAP 服务器守护程序
- apache-spark - 如何使用 Spark Session 列出 S3 存储桶中的文件?
- javascript - 如何在 javascript 中设置 cookie?TT(Django 项目)
- php - 通过键排列查找值,php
- kubernetes - 如何使用 PodTemplate