I have always had trouble with doing this - calling variables from another script.
I have a c# script that calculates gold, and a c# script for enemy AI, including a health variable, etc… What I want, is when the enemy’s HP goes down to 0 or below, a certain amount of gold is given to the player. That means, accessing the gold script and adding an amount to the total gold.
How can I do this?
Thanks in advance!
You don’t need to have a static variable to do this. For example: Let’s say you have a gameObject named “Player1”, and another one named “Enemy1”. Enemy1 has a script called “EnemyHealth”. To access this, you first access the gameObject, then the script on the object, then the variable “hp” from that EnemyHealth script. This would work like so:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
GameObject Enemy1;
int enemyHP;
int increment = 100;
void Update()
{
if(GameObject.Find("Enemy1"))
{
Enemy1 = GameObject.Find("Enemy1");
enemyHP = Enemy1.GetComponent<EnemyHealth>().hp;
if(enemyHP <= 0)
{
GetComponent<GoldClass>().gold += increment;
Destroy(Enemy1);
}
}
}
}
This isn’t specific because it is just an example. This simply focuses on how to access a variable from a script on another gameObject without needing to use static (single instance) variables. Click here for more information on GetComponent
int other = gameObject.GetComponent(ScriptName).newNo;
Another method : Make into
public static int newNo;
Get variable as
int otherNo = ScriptName.newNo;
Another method is that you can make into playerprefs
PlayerPrefs.SetInt("PlayerScore", 10);
And get as
PlayerPrefs.GetInt("PlayerScore");
You have multiple possibilities:
You can add a public method to the gold script:
public void AddGold (int amount)
{
this.gold += amount;
}
That allows a controlled gold management, but isn’t the most simple way.
You can also make the variable “gold” public so that the script can directly access the variable. But that isn’t a very clean way (but it works).
To access the method or public field, you can use:
// Get the script that manages the gold of the player
var gScript = (GoldScript)player.GetComponent("GoldScript");
// If you choose the way with the public field, use this line to add gold
gScript.Gold += 50;
// Else use this line of code
gScript.AddGold(50);
“GoldScript” is the script that manages the gold
“player” is the gameobject that contains the script
Hope I was able to help.
Greetings
Chillersanim
Although the answers above are acceptable, if you know that there is only one GoldScript in the scene you could use a singleton pattern and call
GoldScript.instance.Gold += 50
or whatever mechanism you use.