Beginner Scripting: GetComponent



This weeks coding task looked at the GetComponent function. This function helps to access other scripts attached to the same game object. A key factor in this is that there must be public variables, not private in order to obtain. It can also be used to access other components that are not exposed by the API. It uses up a lot of processing power and shouldn't be used over and over as this will waste a lot of your processing time. Its good practice to call it in the Awake or Start functions or only once when its first needed.


The script is as follows


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

AnotherScript

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

YetAnotherScript

using UnityEngine; using System.Collections; public class YetAnotherScript : MonoBehaviour { public int numberOfPlayerDeaths = 3; }

Comments

Popular Posts