GetComponent

Evidence

Script #1

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”);
    }
}

Script #2

using UnityEngine;
using System.Collections;

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

Script #3

using UnityEngine;
using System.Collections;

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

Screencast

What I Learned

This tutorial taught me how to reference different scripts and GameObjects through one script so that their values can be changed in the hierarchy view of Unity. The scripts were relatively simple to copy down and the tutorial was easy to follow, so the only problem I had was making sure everything was accurate in the scripts so they would function correctly when attached to my cube.

Leave a Reply

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