- Home /
Selecting a component of gameObject
Hi , I AM ROOKIE In unity please help me first of all i should say that i searched but i cant find my answer so i have a empty game object that i assigned the script in it: here is the script using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Gear_setup : MonoBehaviour {
public GameObject gear;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Text Gear = GetComponent ("Text").text;
Debug.Log (Gear);
}
}
and i dragged and dropped the other game object on public GameObject gear;
section on that code the problem is the game object that i assigned to gear has a text and i want to Debug.log("THE TEXT"); how can i do that ?
Answer by ShadyProductions · Aug 01, 2017 at 08:31 PM
Never use GetComponent in update, as this is an expensive call. And you don't want to call it every frame.
Instead cache it inside a variable in the class scope.
public class Gear_setup : MonoBehaviour {
public GameObject Gear;
private Text _textComponent;
// Use this for initialization
void Start () {
_textComponent = Gear.GetComponent<Text>();
Debug.Log(_textComponent.text);
}
}
the gear text is changing evert time that the car moving so
i need to know that every frame, so that is why i put the Debug part in update
in u'r solution the gear is been shown once , but i want to know the value of that every frame
what can i do ?
Then put the debug in the update, but never use GetComponent in update. Like:
public class Gear_setup : $$anonymous$$onoBehaviour {
public GameObject Gear;
private Text _textComponent;
// Use this for initialization
void Start () {
_textComponent = Gear.GetComponent<Text>();
}
void Update() {
Debug.Log(_textComponent.text);
}
}
Answer by look001 · Aug 01, 2017 at 08:42 PM
I'm not completely sure what you mean. As i understand you have a GameObject "gear" with a Textcomponent applied to it. To show the text in the console you need to change a bit.
void Start () {
string text = gear.GetComponent<Text> ().text;
Debug.Log (text);
}
Also you need to import "UnityEngine.UI" to use the Text class. For that you add the line using UnityEngine.UI;
to the top. Btw. it's recommend to write variable names with a capital letter. Methods and Classes start with a Capital letter. Good Luck!