How to access another public variable from another script or gameobject?

Let’s say I have

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class HitController : MonoBehaviour {

    public int level;
   

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

How do I access the ‘level’ variable from another script?

You can attach HitController to a game object in your scene, let’s say “Player”, and then from any other script you can do this:

 HitController _hitController = GameObject.Find ("Player").GetComponent<HitController> ();

int myLevel = _hitController.level;
1 Like

Thanks that worked, can you find the gameobject by tag instead of name, and what would be the syntax?

Yes, I imagine you could do something like this:

GameObject[] _playerGameObjects;

_playerGameObjects = GameObject.FindGameObjectsWithTag("Player");

Thanks will try it tomorrow, just going to bed now!

There are a bunch of other ways to get GameObject references too.