0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

(4)大空と大地の中で#1

Last updated at Posted at 2020-05-14

僕は[RequireComponent()]を理解しなければなりません!

リファレンスには、
これはセットアップエラーを回避するのに役に立ちます、、、?
忘れ物をなくすための機能?
わざわざ追加して書く必要があるものなのか?
本当、よく分からない

よし、使ってみよう。
でも使い方が、そもそも分からない。

そこで作戦

1)RequireKnightオブジェクトを作成して
2)Rigidbodyコンポーネントをつけよう。
3)RequireTestスクリプトを作成してそこに[RequireComponent()]と適当にRigidbody取得的なこととか書こう。
で、
4)Rigidbodyコンポーネントをはずしちゃおう。

その時に何が起こるのか?

1)RequireKnightオブジェクトを作成して

0000.JPG

2)Rigidbodyコンポーネントをつけよう。

0001.JPG

3)RequireTestスクリプトを作成してそこに[RequireComponent()]と適当にRigidbody取得的なこととか書こう。

public class RequireTest : MonoBehaviour
{
    Rigidbody rigid;

    void Start()
    {
        // リジッドボディを取得
        rigid = this.GetComponent<Rigidbody>();

        // 適当に
        if (rigid.useGravity == true)
        {
            // 重力を無効にする
            rigid.useGravity = false;
        }
    }
}

そしてついに

4)Rigidbodyコンポーネントをはずしちゃおうっと。

001.gif

僕は[RequireComponent()]を理解しなければなりませんでしたが

[RequireComponent()]をつけてませんでした。

[RequireComponent()]()の中には何入れるのよ?という「疑問」
こうらしい、、、
[RequireComponent(typeof(Rigidbody))]
RequireComponent(typeof(コンポーネント名))]

出来た!ので検証、、、

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]

public class RequireTest : MonoBehaviour
{
    Rigidbody rigid;

    void Start()
    {
        // リジッドボディを取得
        rigid = this.GetComponent<Rigidbody>();

        // 適当なif文
        if (rigid.useGravity == true)
        {
            // 重力を無効にする
            rigid.useGravity = false;
        }
    }
}

002.gif

なるほど、コンポーネントをつけてると既にはずせない。

じゃあ、もともとコンポーネント付けてなかったら?

05.gif

必要なコンポーネントを自動でつけてくれるんやー

参考にさせて頂いたサイト

スクリプトリファレンス
Require ComponentとReset()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?