I’m trying to send a string from
BattleCalculations.cs (a script in a folder, not attached to anything)
to
BattleGUI.cs which is attached to BattleCanvas gameobject
where a method is
public void GameMessage(string words){
gameText.text = gameText.text + “\n” + words;
}
I’ve tried referencing the BattleGUI script within BattleCaculations.cs with
private BattleGUI battleGUIScript = new BattleGUI();
and using this code
battleGUIScript.GameMessage(user + " used " + userUsedAbility.AbilityName);
and I get this error
NullReferenceException: Object reference not set to an instance of an object
BattleGUI.GameMessage (System.String words) (at Assets/Scripts/Turn Based Combat/BattleGUI.cs:114)
Basically I set up a method in my BattleGUI script so that other scripts could send messages to it and the messages would show up in game. “Matt used Wind Slash.” “Matt did 200 damage to Enemy.” etc.
Any help would be very appreciated.
Okay I think it’s because BattleCalculations.cs doesn’t have a gameText variable defined, so I’d have to set one up.
But it seems like an awful lot of work to have to setup a new gameText reference and connection to BattleGUI.cs for each file wanting to send a string to BattleGUI.cs.
There has to be another way.
when i make the method
public void GameMessage(string words){
Debug.Log (words);
}
it will work alright, but when it has to adjust gameText.text that is inside the BattleGUI.cs script, it fails.
I tried making gameText public, but it didn’t help.
I DID IT! I DID IT! I FIGURED IT OUT!
After trying so many things, I finally got it to work.
So BattleGUI.cs still defines gameText at the top
private Text gameText;
but inside of the method
public void GameMessage(string words){
gameText = GameObject.Find (“GameText”).GetComponent();
gameText.text = words;
}
instead of drawing the reference to the Text component from outside the function, which leaves any other script clueless on the path to the Text component, I set the path inside the method, so any other script can follow it. Maybe not the best explanation, but I hope people understand.
and of course I put
private BattleGUI battleGUIScript = new BattleGUI();
in BattleCalculations.cs script and just called the method and sent the variable and it worked.
my only concern, now that it is working, is that the path to the Text component is being drawn over and over and over again. I’m not sure if that is sloppy or slow coding or what. If anyone has a better suggestion, I’d LOVE to hear it.