Menu Close

GetComponent

Okay, so I still don’t totally understand the GetComponent function. I’ve tried using it in a script but I’m doing something wrong and I don’t have enough time to keep messing around. But basically it is a way of accessing variables from a different script within or not within the same game object. In their example they have AnotherScript and YetAnotherScript in which they access the variables that each of them contains. And uses it in the script UsingOtherComponents.

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");
    }
}
using UnityEngine;
using System.Collections;

public class AnotherScript : MonoBehaviour
{
    public int playerScore = 9001;
}
using UnityEngine;
using System.Collections;

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

https://unity3d.com/learn/tutorials/topics/scripting/getcomponent

Leave a Reply

Your email address will not be published. Required fields are marked *