官术网_书友最值得收藏!

The RequireComponent attribute

Currently, we are using the Rigidbody component in order to create our script. When working as a team member, others may not be reading your scripts, but are still expected to use them when creating gameplay. Unfortunately, this means that they may do things that have unintended results, such as removing the Rigidbody component, which will cause errors when our script is run. Thankfully, we also have the RequireComponent attribute, which we can use to fix this.

It looks something like this:

using UnityEngine; 

[RequireComponent(typeof(Rigidbody))]
public class PlayerBehaviour : MonoBehaviour

By adding this attribute, we state that when we add this component to a game object and it doesn't have a Rigidbody attached to its game object, the component will be added automatically. It also makes it so that if we were to try to remove the Rigidbody from this object, the editor will warn us that we can't, unless we remove the PlayerBehaviour component first. Note that this works for any class extended from MonoBehaviour; just replace Rigidbody with whatever it is that you wish to keep.

Now, if we go into the Unity editor and try to remove the Rigidbody component by right-clicking on it in the Inspector and selecting Remove Component, the following message will be seen:

This is exactly what we want, and this ensures that the component will be there, allowing us not to have to include if-checks every time we want to use a component.

主站蜘蛛池模板: 建德市| 外汇| 崇仁县| 察雅县| 通化县| 钟山县| 增城市| 定西市| 图们市| 淮北市| 太康县| 台南县| 广灵县| 卓资县| 彰化县| 二连浩特市| 舟山市| 新泰市| 岗巴县| 宁陕县| 博罗县| 九龙县| 灵台县| 高要市| 秦皇岛市| 北票市| 剑河县| 鲁山县| 曲水县| 始兴县| 航空| 綦江县| 霍州市| 翼城县| 缙云县| 秦皇岛市| 南阳市| 成都市| 雅江县| 龙海市| 治县。|