- Unity 2017 Mobile Game Development
- John P. Doran
- 245字
- 2021-07-02 22:27:45
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.
- Flask Web全棧開發實戰
- Facebook Application Development with Graph API Cookbook
- Mastering AWS Lambda
- 看透JavaScript:原理、方法與實踐
- Mastering React
- C++反匯編與逆向分析技術揭秘(第2版)
- Statistical Application Development with R and Python(Second Edition)
- Regression Analysis with Python
- Illustrator CC平面設計實戰從入門到精通(視頻自學全彩版)
- 零基礎學C語言(升級版)
- Google Adsense優化實戰
- SQL Server on Linux
- Building Microservices with Go
- INSTANT Apache Maven Starter
- 人件集:人性化的軟件開發