- Home /
Get variables from other scripts
How can you get a variable from another scipt? Is it even possible? I don't need a specific example, just something general.
Answer by Eric5h5 · Mar 03, 2011 at 10:07 PM
This is covered in the docs: http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html. You should generally avoid static variables unless you specifically need them, since only one instance can exist per class/script. For example, this is a fail:
// EnemyScript.js static var enemyHealth = 100; // bad!
// PlayerScript.js function DoDamage (damage : int) { EnemyScript.enemyHealth -= damage; if (EnemyScript.enemyHealth <= 0) { Destroy (enemy); } }
All enemies would then have the exact same health, since "enemyHealth" would be shared across all objects using that script. Instead of static variables, use public variables with GetComponent and so on, or better yet use private variables, and access public interfaces instead (less chance of bugs that way). For example, here's a more correct way of handling the above scripts:
// EnemyScript.js var startingHealth = 100; // can be changed in the inspector private var enemyHealth : int;
function Start () { enemyHealth = startingHealth; }
function Hit (damage : int) { enemyHealth -= damage; if (enemyHealth <= 0) { Destroy (gameObject); } }
// PlayerScript.js function DoDamage (damage : int) { enemy.GetComponent(EnemyScript).Hit(damage); // You might also do this: // enemy.SendMessage("Hit", damage); }
How the "enemy" variable is defined in those scripts would depend on what you're doing exactly; you might use GameObject.Find, or the results of raycasting, or whatever.
I seem to be getting an odd error when attempting to use
"var x : float = transform.parent.GetComponent(ScriptOneLevelUp).variableInThatScript;"
It results in the error: "NullReferenceException: Object reference not set to an instance of an object LowerLevelScript.Update () (at Assets/Scripts/LowerLevelScript.js:lineNumber)"
The link doesn't work. I suspect it should point to here: http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
$$anonymous$$eep in $$anonymous$$d, when they write "OtherScript" they mean the name of your other script, $$anonymous$$us the file type (so myScript.js would be myScript). Just posting for someone else, like me, looking for the answer to a similar but distinct question. :)
Sorry if I wind up Necro-ing this, but this is sending the variable to the other script, rather than pulling it from one. It works the same way, but you gotta think opposite of what brought you here. ("Send script A to script B" ins$$anonymous$$d of "Pull script B into script A".)
can't you specify which gameobject you access i.e. static var...
enemy1.enemyscript.damage
Answer by Uriel_96 · Mar 03, 2011 at 09:18 PM
you can also use static variables:
//the script is called ScriptExample
static var example = false;
function Update(){
//blablabla
}
in another script put:
function Update(){
if(/*Press or do soemthing*/){
ScriptExample.example = true;
}
}
and you can also use SendMessage, but this works not for script, this is by using the object:
var example = false;
var object1 : GameObject;
function Start(){
object1.SendMessage("DoSomething", example);
}
function DoSomething(example){
example = true;
}
VERY HELPFUL..However, for newbies like myself, we sometimes need a bit more "spoon feeding". It was NOT obvious at first, that what you are doing in he 2nd script is referring to the first script then the static variable in that script. ScriptExample in 2nd script above is shown in purple and I thought this was a Unity built in function. It is also helpful to suggest where to put these scripts, I put my first script onto a empty gameobject in the scene. Again, thanks! Was pulling my hair out on this one.
This helped me a lot. I did need to change it to "public static var example = false;" when declaring the variable, though, to make it accessible to other scripts.
Answer by efge · Mar 03, 2011 at 09:14 PM
You could use GetComponent:
"You can access script components in the same way as other components."
Answer by RealSoftGames · Jul 08, 2015 at 04:21 AM
Ok for this general reason their are several ways to do this, for example we will use Health as a common factor for this.
//------------------------------------------------------------------------------------------
Response Language is in C#
This small piece wall of text below will demonstrate 2 ways to talk to gameobjects and their scripts.
Example1: is using a raycast, Expected you know how to do one, this does not work with copy paste, it requires the rest of the raycast code to work.
Example2: we demonstrate an interactive ShopSystem, shop has items for sale, player presses P to open shop and shopKeeper telsl the player what items she/he has for sale. you press 1,2 or 3 and it purchases an item from the shop deducting money from the Player script on the game object. this is a very small script and does not present any checking at all, when you purchase an item the correct amount will be deducted from your gold.
Example2: works if you copy paste the scripts exactly and follow the image provided with correct linking.
if anything in this demo seems unclear of how it works, don't hesitate to contact me at
krazor.voidstartgames@gmail.com or through youtube using the same email.
//------------------------------------------------------------------------------------------
Example 1:
using raycast for hit
/checks if we hit anything at all, and also checks if we hit something with a tag of TheTagToApplyDamageTo /
if (hit.collider != null || hit.collider.tag == "TheTagToApplyDamageTo") { hit.collider.enabled = false; /sets the target's collider we hit to false, now to access a script and component, we will use a script named Health as example. /
hit.collider.GetComponent().curHp -= Damage;
/* assuming your target has a script called Health on it and a variable curHp and this script has a variable Damage, we are essentially saying when we hit something with a raycast we want to talk to it that is defined by hit.collider you can test what you hit by doing hit.collider.name, this will print the gameObjects name in console. now when we do .GetComponent, the other part of this is saying i would liek to talk to the object(otherwise known as component) this is determined by the raycast you just used to hit it, now this is where it gets fun. in the <> will determine what scripts are accessible on the component. hit.collider.GetComponent() the () is required, think of it like this, we use () at the end of functions wtc, think of it as a do something && a call piece. so we do hit.collider.GetComponent().curHp now we have access to any gameobject we hit with our raycast that has a script called Health attached to it. and for curHp, this is public int curHp = 100; on our Health Script. remember to have the script set to public to be accessible. public class Health: MonoBehaviour {
*/ }
Example2: OPEN IMAGE IN NEW TAB TO SEE FULL SCREENSHOT! this will demonstrate what the below code will do and how to test it for your self.
you can access any script on a game object. you do not even need to use a raycast, if you know a specific gameobject's script you want to access,
if you have a gameobject called shop and one called player. in this example we will interact with a shop system.
what we will use is 2 gameobjects
/Gameobject Interact/ //scripts attatched Interact
using UnityEngine;
using System.Collections;
public class Interact: MonoBehaviour {
public GameObject shop;
public float Cash = 5000;
void Start()
{
shop = GameObject.Find("Shop");
print ("Press P to open Shop!");
}
void Update()
{
if(Input.GetKeyDown(KeyCode.P))
{
//press P to get item prices From Shop
shop.GetComponent<ShopSystem>().Inventory(); //this will run the function in ShopSystem script, on the Shop Object
}
if(Input.GetKeyDown(KeyCode.Alpha1))
{
//when we press key 1 we will purchase a Sword from the shop and deduct money from our game Object
shop.GetComponent<ShopSystem>().BuySword();
print ("Gold $" + Cash + " Left");
}
if(Input.GetKeyDown(KeyCode.Alpha2))
{
//when we press key 2 we will purchase a Axe and deduct money from our game Object
shop.GetComponent<ShopSystem>().BuyAxe();
print ("Gold $" + Cash + " Left");
}
if(Input.GetKeyDown(KeyCode.Alpha3))
{
//when we press key 3 we will purchase a Mace and deduct money from our game Object
shop.GetComponent<ShopSystem>().BuyMace();
print ("Gold $" + Cash + " Left");
}
}
}
/Gameobject Shop/ //scripts attatched ShopSystem
using UnityEngine;
using System.Collections;
public class ShopSystem: MonoBehaviour {
//assume i have actual gameObjects with these names attatched to the slots.
public GameObject Sword,Axe, Mace;
public float SwordPrice = 499.99f, AxePrice = 200.75f, MacePrice = 100.50f;
public float price;
GameObject player;
//note the functions are public, this allows them to be accessed through other scripts.
void Start()
{
player = GameObject.Find ("Interact");
}
public void Inventory()
{
print("Welcome to my Store!");
print("key 1 to Buy " + Sword.name + " $499.99");
print("key 2 to Buy " + Axe.name + " $200.75");
print("key 3 to Buy " + Mace.name + " $100.50");
}
public void BuySword()
{
print ("You purchased " + Sword.name);
player.GetComponent<Interact> ().Cash -= SwordPrice;
}
public void BuyAxe()
{
print ("You purchased " + Axe.name);
player.GetComponent<Interact> ().Cash -= AxePrice;
}
public void BuyMace()
{
print ("You purchased " + Mace.name);
player.GetComponent<Interact> ().Cash -= MacePrice;
}
}
please find the image below with results of what to expect, this is only 2 ways to access gameobjects using a raycast and accessing manually with Getcomponent.
their are several other ways, you can use collision, trigger, Distance Check, you could even use GameObject.SendMessage, which i believe is another function call built into unity. you can obtain details very easily such as RequireReciever to obtain more detailed info if you hit the target for example, send data back to the attacker etc. this is also doable without using SendMessage. but creating your own function to do so.
SendMessage, is pretty much a function call.
//API Links for more details SendMessage API Link http://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
GetComponent API Link
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
Answer by poncho · Mar 03, 2011 at 09:27 PM
you need to give the variable you want to read the privileges if you want to use the variable using an object make it public if you want to use the variable using just the class make it static
by the way, yes it is possible
Your answer
![](https://koobas.hobune.stream/wayback/20220613111243im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Maths with variables 2 Answers
Acces to a var from another Script. 2 Answers
Function variable problem. 1 Answer