LoginSignup
5
4

More than 5 years have passed since last update.

GetComponentの基本を理解する

Posted at

はじめに

1から勉強すると必ず出るメソッドです。写経を行いテキストの指示通りにやればほぼうまくいきます。しかしこれらを繰り返していくといざ説明する時に、何も理解をしていない事に気が付きました。テストを繰り返していくうちに理解できるようになったので、記事にします。

Componentとは

Inspectorに表示されているTransform以下の各々の情報。AddComponentでGameObjectで使うコンポーネントを追加します。GetComponentはこれらの情報を変数に割り当てることで、自由に設定できます。
component2.png

スクリプト

public class CylinderRotate : MonoBehaviour
{
    float time;  

    void Update()
    {
        time += Time.deltaTime;                   //timeを加算し続ける
        var ren = GetComponent<Renderer>();       //コンポーネントRendererを取得
        var col = GetComponent<Collider>();       //コンポーネントColliderを取得
        var tra = GetComponent<Transform>();      //コンポーネントTransformを取得

        tra.Rotate(10f, 0, 0);    //GameObjectoを回転させる。

        if(time >= 0)             //timeが0秒経過
        {
            col.enabled = true;   //Colliderを真
            ren.enabled = true;   //Rendererを真
        }

        if(time >=2)               //timeが2秒経過
        {
            col.enabled = false;   //Colliderを偽
            ren.enabled = false;   //Rendererを偽

            if (time >=4)          //timeが4秒経過
            {
                time = 0;          //timeを0にする。
            }
        }
    }
}

上のスクリプトを打ちこんで、3Dオブジェクトにアタッチする。

結果

movie.gif

感想

今までコンポーネントの使い方は理解をほとんどしていなかったが、ロックマンのような足場を消す・現れるの繰り返しを作ってみたことで、理解が大分進んだと思う。

5
4
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
5
4