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!!

3 Answers

3

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 "MyClass" wasn't MonoBehaviour? Or would I use another way?

–

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);
        }
}

For this example, and many others, this is the most simple solution. Any way, if the object rotates, scaled, or parent is changed the object will be kind of moving... Most of the places I know they check for if object not moving will be best using this method.

–

Hi, I think to having wrote in right place;

I defined a class named LvlManager:

using UnityEngine;
using UnityEngine.SceneManagement;

public class LvlManager : MonoBehaviour
{
    
    public static LvlManager Instance { get; private set; }
    
    [Header("References")]
    public static int level = 0 ;
    public Transform startPos;
    public Transform[] path;
    public int path_idx = 0;
    
    [SerializeField] public int killingsToGet; // minimum number of killed enemy to win !!
    [SerializeField] public static int totalEnergy;
    [SerializeField] public static GameOver gameOver;
    [SerializeField] public WINNING_bg wining;
    
    public bool gameRunning;
    public static int money;
    public static  int killedEnemies; 

    private void Awake()
    {
        Debug.Log("LevelManager Awake");
        
        gameRunning = true;
        
        
        if (Instance != null && Instance !=this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        money = 8; // starting value
        
        totalEnergy = 3;
        killedEnemies = 0;
        
        
        DontDestroyOnLoad(gameObject);

        
    }

    
    private void  Update()
    {
        if (killedEnemies >= killingsToGet) // WON condition killingsToGet
        {
            if (wining != null)
            {
                Win_Window();
            }
            
        } 
        
    }
    
    public void LoadNextLevel() { 
        int nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1; 
        if (nextSceneIndex < SceneManager.sceneCountInBuildSettings)
        { 
            SceneManager.LoadScene(nextSceneIndex); 
            } else 
            { Debug.LogWarning("Sei già all'ultimo livello! "); 
           
            } 
        }
    //
    public static void Game_Over()
    {
        
        
        gameOver.setting();
    }

    public void Win_Window()
    {
        if (wining != null)
        {
            wining.winning();
            
        }
        else
        {
            return;
        }
        
        
    }
   
}

If try to accessing the LvlManager class within another script like the following:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using LvlManager;


public class Menu_TD : MonoBehaviour
{
    
    [Header("tefers")]
    [SerializeField] TextMeshProUGUI currencyMoneyUI;

    private void OnGUI()
    {
        currencyMoneyUI.text = LvlManager.Intance;   // accessing mistake
        
    }

}

Looks like The type LvlManager, cannot be recognized and so, I cannot access its fields… :kissing_face:

This thread is 7 years old. Make a new thread with your question.

–

holy necro batman!

–