- Home /
How Do I Modify This Variable in Another Script?
I have this script that I allow a player to select his character. It's ChooseAnimal.js:
var animal = "Animal";
function OnGUI() {
if (GUI.Button(new Rect(Screen.width/2-60, 100, 100, 30), "Dog")) {
animal = "Dog";
Application.LoadLevel("JunkYard");}
if (GUI.Button(new Rect(Screen.width/2-60, 140, 100, 30), "Cat")) {
animal = "Cat";
Application.LoadLevel("House");}
if (GUI.Button(new Rect(Screen.width/2-60, 180, 100, 30), "Mouse")) {
animal = "Mouse";
Application.LoadLevel("Sewer");}
}
Then I have this script which exists in the scene that will be used to instantiate that animal on the next screen as well as do some other stuff. It's called character.js:
var animal = "Animal";
var skill = "Skill";
var street = "Street";
function Awake () {
DontDestroyOnLoad (transform.gameObject);
}
How do I get the Character.js to use the variable "animal" in ChooseAnimal.js?
This question is asked frequently. Google "How Do I $$anonymous$$odify This Variable in Another Script Unity3d" for many answers. Plus this resource:
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Components.html
1 answer: How does DoSomething make variable A in script 1 modify variable in script B?
... this forum is strictly ordered into questions, answers and comments. its a QA forum
"access variable from another script" to reference animal from character script.
Answer by SecondMouse · Feb 14, 2014 at 03:22 AM
While that is the article that I was looking for (thank you very much), it doesn't really tell me how to make my variable in one script, change a variable in another. It mearly says
otherScript.DoSomething();
How does DoSomething make variable A in script 1 modify variable in script B? I understand Translate and AddForce, but I'm just trying to access and change a name or number.
Found the answer. Thank you. The script that was needs to modify the variable in the other script needed this code:
var scriptTarget : Character;
var animal = "Animal";
function OnGUI() {
if (GUI.Button(new Rect(Screen.width/2-60, 100, 100, 30), "Dog")) {
scriptTarget.animal = "Dog";
Application.LoadLevel("JunkYard");}
if (GUI.Button(new Rect(Screen.width/2-60, 140, 100, 30), "Cat")) {
scriptTarget.animal = "Cat";
Application.LoadLevel("House");}
if (GUI.Button(new Rect(Screen.width/2-60, 180, 100, 30), "$$anonymous$$ouse")) {
scriptTarget.animal = "$$anonymous$$ouse";
Application.LoadLevel("Sewer");}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613133432im_/https://answers.unity.com/themes/thub/images/avi.jpg)