- Home /
Accessing a Class From Another Script
This is probably a foolish question but is there a possibility to access a class from another script? I know you can attach it to a gameobject then get the script from the component. But for my case I'm using a class that holds my coins so that they can be saved. The saving script accesses the file no problem. But when I apply the same logic to another script it gives me an error " 'somescript' is never assigned to, and will always have its default value null" public class CoinTracker { private int _coins; public CoinTracker () { } public CoinTracker(int coins) { _coins = coins; } public int coins { get { return _coins; } set { _coins = value; } } }
And then the "SomeScript:MonoBehaviour" is like this:
{
private CoinTracker coinTracker;
// Start is called before the first frame update
void Start()
{
Debug.Log(coinTracker.coins);
}
}
I am just really confused because the "Saving" script accesses the "Cointracker" class just like it is shown in the "SomeScript". Any light or possible ways to access the class directly if possible would be awesome. Thank you!!
Answer by highpockets · May 26, 2019 at 10:43 PM
public class MyClass : MonoBehaviour
{
//lots of fun stuff in this class
}
Above is the script you want to access from another script, which is below:
public MyOtherClass : MonoBehaviour
{
[SerializeField] MyClass firstScript;
}
Now in the inspector, just click on the little circle to the right of the field and it will show you the instances of the type your looking for if they exist and you put it in there.
Thanks! One question, would I use that same method if "$$anonymous$$yClass" wasn't $$anonymous$$onoBehaviour? Or would I use another way?
Same way. $$anonymous$$onoBehaviour classes just have more capabilities in unity, but you don’t need to use them if you don’t need those abilities
Answer by Zankomag · May 27, 2019 at 10:57 PM
In your case you had better use Singleton for CoinTracker if you want only one instance of this class:
public class CoinTracker
{
public static CoinTracker Instance { get; private set; } = new CoinTracker();
private CoinTracker(){ }
public int Coins { get; set; }
}
Now you can get Coins from anywhere and without assigning it in Inspector every time:
public class SomeScript : MonoBehavior{
void Awake(){
print(CoinTracker.Instance.Coins);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612202135im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
should class members ever be static? 1 Answer
How to select a variable from another GameObject by accessing the class in the Inspector. 2 Answers
Best programming practice for making in game menus 0 Answers
Accessing an object through a direct reference or a pointer 1 Answer
How do I change a variable in Script A from inside Script B 1 Answer