- Home /
GuiText Problem
Sup, guys. I've written the next script:
using UnityEngine;
using System.Collections;
public class Gold : MonoBehaviour {
private KingController KingController;
void Awake() {
KingController = GetComponent<KingController>();
}
//comment
void Update () {
string format = System.String.Format("Gold:", KingController.Gold);
guiText.text = format;
}
}
But Unity says that 12 lane cause this error: I wanted to display int "Gold", taken from other script, but something goes wrong. Don't get it, what's wrong =( Help pls
Is the $$anonymous$$ingController script attached to this game object? GetComponent() won't find it if it is attached to some other game object.
Ehm, what? GetComponent() uses to address properties of other scripts or components =) Or maybe i could be mistaken, but if so, how can i then get component from script on other object?
You need a reference to the game object that contains the script. You can use GameObject.Find() to get the reference, or you can create a public variable and drag and drop the game object onto the variable in the inspector.
GameObject go = GameObject.Find("GameObjectThatContains$$anonymous$$ingController");
kingController = go.GetComponent<$$anonymous$$ingController>();
Also variables (by convention) should start with a lower case letter and never be named the same as the class.
Answer by FusionSausage · Oct 12, 2013 at 02:56 PM
I would say instead of using getComponent trash that row and in the KingController script add this line instead of your declaration:
public int Gold { get{ return gold; } set{ gold=value; } }
Now you only need to type KingController.gold in your Gold class and it's better because you can both get and change (set) the variable in your Gold class.
And are you sure that you have spelled KingController right, in all ways (capital letters) and such? That was a problem I had.
I've used robertu's way, but anyway thx for attention =)
No problem, but remember that there is always this method that is very good for getting variables from other scripts :)