how to access variable in another file unity code example
Example 1: unity how to use variable from another script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Miner : MonoBehaviour // A class made to mine coins
{
private Variables variables; // "Variables" is the class name with my variables in it, "variables" is the name of it's variable in this class
void Start()
{
variables = GameObject.Find("ScriptHolder").GetComponent<Variables>(); // "ScriptHolder" is the name of the GameObject that holds the Variables class
}
public void Mine()
{
variables.coins += variables.minePower; // This is how you reference your variables
}
}
Example 2: how to reference a variable from another script in unity
public class PointScript : MonoBehaviour { public static int playerScore; // Static keyword makes this variable a Member of the class, not of any particular instance. void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") playerScore++; // The code that any instance can use to cause the score to be incremented, since the playerScore variable is a Static member, all instances of this class will have access to its value regardless of what instance next updates it. } }