GetComponent

確認済のバージョン: 4

-

難易度: 初級

他のスクリプトやコンポーネントのプロパティーを処理する GetComponent 関数の使い方を学びます。

GetComponent

初級 Scripting

UsingOtherComponents

Code snippet

using UnityEngine;
using System.Collections;

public class UsingOtherComponents : MonoBehaviour
{
    public GameObject otherGameObject;
    
    
    private AnotherScript anotherScript;
    private YetAnotherScript yetAnotherScript;
    private BoxCollider boxCol;
    
    
    void Awake ()
    {
        anotherScript = GetComponent<AnotherScript>();
        yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
        boxCol = otherGameObject.GetComponent<BoxCollider>();
    }
    
    
    void Start ()
    {
        boxCol.size = new Vector3(3,3,3);
        Debug.Log("The player's score is " + anotherScript.playerScore);
        Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
    }
}
#pragma strict

public var otherGameObject :  GameObject;


private var anotherScript : AnotherScript;
private var yetAnotherScript :  YetAnotherScript;
private var boxCol : BoxCollider;


function Awake ()
{
    anotherScript = GetComponent(AnotherScript);
    yetAnotherScript = otherGameObject.GetComponent(YetAnotherScript);
    boxCol = otherGameObject.GetComponent(BoxCollider);
}


function Start ()
{
    boxCol.size = new Vector3(3,3,3);
    Debug.Log("The player's score is " + anotherScript.playerScore);
    Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
}
import UnityEngine
import System.Collections


public class UsingOtherComponents(MonoBehaviour):

    public otherGameObject as GameObject

    
    
    private anotherScript as AnotherScript

    private yetAnotherScript as YetAnotherScript

    private boxCol as BoxCollider

    
    
    private def Awake():
        anotherScript = GetComponent[of AnotherScript]()
        yetAnotherScript = otherGameObject.GetComponent[of YetAnotherScript]()
        boxCol = otherGameObject.GetComponent[of BoxCollider]()

    
    
    private def Start():
        boxCol.size = Vector3(3, 3, 3)
        Debug.Log(('The player\'s score is ' + anotherScript.playerScore))
        Debug.Log((('The player has died ' + yetAnotherScript.numberOfPlayerDeaths) + ' times'))

AnotherScript

Code snippet

using UnityEngine;
using System.Collections;

public class AnotherScript : MonoBehaviour
{
    public int playerScore = 9001;
}
#pragma strict

public var playerScore : int = 9001;
import UnityEngine
import System.Collections


public class AnotherScript(MonoBehaviour):

    public playerScore = 9001

YetAnotherScript

Code snippet

using UnityEngine;
using System.Collections;

public class YetAnotherScript : MonoBehaviour
{
    public int numberOfPlayerDeaths = 3;
}
#pragma strict

public var numberOfPlayerDeaths : int = 3;
import UnityEngine
import System.Collections


public class YetAnotherScript(MonoBehaviour):

    public numberOfPlayerDeaths = 3

関連するチュートリアル