- Home /
How to pass string from one script to another in C#
I am need to know the value of a string located in a different scriptin C#. I need to get the string from a script called GameManager
. The script is applied to a game object called _GameManager
I have also attached a tag to the game object called _GameManger
.
The string I need from the GameManger
script is called suspectName
. I need to pass it into a script called CharacterTile
that is attached to a game object called CharacterTile
and has the tag CharacterBox
.
Hope this isn't to confusing.
Getting access to other game objects is the most asked question on UA. A couple of links:
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
See the GetComponent sections here: http://unitygems.com/
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Components.html
Also you may check this question
Answer by Erisat · May 10, 2014 at 07:30 AM
in CharacterTile:
string suspectName = "";
void Start()
{ //correction below, thanks to robertbu for pointing out mistake
GameManager gameManager = GameObject.Find("_GameManager").GetComponent("GameManager") as GameManager; suspectName = gameManager.SuspectName();
}
and then in GameManager declare:
public string SuspectName() { return suspectName }
hope this helps.
Don't use a string parameter for GetComponent (plus it will generate a compiler error unless you cast things). Use the generic version for C#.
Note the OP did not indicate what language he was writing in.
You are correct, I posted that without actually trying it. Correction is:
string suspectName = ""; void Start() { Game$$anonymous$$anager game$$anonymous$$anager = GameObject.Find("_Game$$anonymous$$anager").GetComponent("Game$$anonymous$$anager") as Game$$anonymous$$anager; suspectName = game$$anonymous$$anager.SuspectName(); }
(i tried it this time, it works. my apologies for earlier post)
Your answer
