Unityな日々(Unity Geek)

Unityで可視化アプリを開発するための試行錯誤の覚書

同階層のComponentにアクセスする

Componentとは、GameObjectに付加する部品のようなもの。一般的には、GetComponent("Component名") で取得する。

javascript

GetComponent(Transform).Translate(0, 1, 0);

C#

using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
    void Example() {
        GetComponent<Transform>().Translate(0, 1, 0);
    }
}

ScriptもComponentの一種なので、同様にアクセスできる。

javascript

function Update () {
    var otherScript: OtherScript = GetComponent(OtherScript);
    otherScript.DoSomething();
}

C#

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        OtherScript otherScript = GetComponent<OtherScript>();
        otherScript.DoSomething();
    }
}


よく使うComponentは変数が定義されている。

Transform transform
Rigidbody rigidbody
Renderer renderer
Camera camera (only on camera objects)
Light light (only on light objects)
Animation animation
Collider collider

名称は小文字で始まることに注意

transform.Translate(0, 1, 0);