- Home /
How do I access a script from a class inside a script.
public class ShopUpgrades : MonoBehaviour
{
[System.Serializable]
public class Upgrade
{
public bool upgradeType {get; set;} // true == Click, false == Passive
public string name {get; set;}
public float upgrade_multiplier {get; set;}
public int max_level {get; set;}
public int current_level = 0;
public float price {get; set;}
public bool isMax = false;
public bool isAvailable {get; set;}
public void UpgradeObject(ref GameObject upgrade_interface) {
if (current_level != max_level) { //Increments the current level by one
current_level++;
}
GetComponent<Budget_tracker>().budget += upgrade_multiplier;
}
}
}
In line 19 I want to access a script named "Budget_tracker" which is inside the same game object with the ShopUpgrades script. I need to modify "Budget_tracker"s variables in the "UpgradeObject" method of "Upgrade" class. I cannot do it in "ShopUpgrades" script because I also need to assign "Upgrade" objects in that script:
public Upgrade someUpgrade = new Upgrade{
upgradeType = true,
name = "someUpgrade",
upgrade_multiplier = 2,
max_level = 5,
price = 10,
isAvailable = true,
};
public Upgrade someUpgrade2 = new Upgrade {
upgradeType = false,
name = "UpgradeName2",
upgrade_multiplier = 2,
max_level = 5,
price = 10,
isAvailable = true,
};
Answer by Captain_Pineapple · Jan 20 at 08:37 PM
Unless you pass a reference to the ShopUpgrades
object along when instantiating an Upgrade
you simply don't.
A "normal" class which is not derived from a Monobehaviour has no concept of GetComponent
.
So add a constructor to Upgrade
and a private field to contain the ShopUpgrades
class.
Could you demonstrate it a little bit on the code. I am really confused :(
something like this:
[System.Serializable]
public class Upgrade
{
private readonly ShopUpgrade _shopUpgrade;
public Upgrade(ShopUpgrade shopUpgrade)
{
_shopUpgrade = shopUpgrade;
}
public UpgradeObject(...)
{
//instead of GetComponent<Budget_tracker>() use:
_shopUpgrade.GetComponent<Budget_tracker>().....
}
}
Thank you so much that solves the problem