Accessing Other Script Variables (C#)

I am having an issue trying to access another script’s variables from another script. Both of these scripts I am referencing to are on separate gameobjects. Script I am trying to access is named “InventoryS2” and the gameobject is named “ThePlayer”. The second script is called “MobT” and the gameobject it is on is called “Cube”.

InventoryS2(Only Showed the relevent code, rest is GUI related things.)

using UnityEngine;
using System.Collections;

public class InventoryS2 : MonoBehaviour 
{
	private int Menu,Options,Inventory,Map,Skills,Stats = 0;
	public Vector2 scrollPosition = Vector2.zero;
	public float GoldCount = 0;

MobT

using UnityEngine;
using System.Collections;

public class MobT : MonoBehaviour 
{
	public float GoldDrop;
	public InventoryS2 Inventory;

	void Awake()
	{
		Inventory = GameObject.Find("ThePlayer").GetComponent ("InventoryS2");
	}

	void OnMouseDown()
	{
		GoldDrop = Random.Range (0,10);
		Inventory.GoldCount = Inventory.GoldCount + GoldDrop;
		Destroy (gameObject);
		Debug.Log (GoldDrop);
	}
}

MobT is designed as a purpose of testing for when I click on the gameobject it will be destroyed and the GoldCount of the InventoryS2 script will increase at random between 1 and ten.

I would like responses that don’t tell me to use static variables.

The problem is that you are using the string version of GetComponent(). When you pass a string to GetComponent(), the type of object you get back is ‘Component’…the base class for all components. This happens because the compiler does not know the type. And you cannot assign a Component class to an InventoryS2 variable without casting (which you are not doing here).

My recommended fix is use the generic version of GetComponent(). Line 11 would then be:

Inventory = GameObject.Find("ThePlayer").GetComponent<InventoryS2>();

What I actually do is Creating 2 public variables.

For example

public NameOfTheReferanceScript objectScript;
public GameObject object;

I am making an Empty GameObject and I assign to it all my screept’s that are not really visible.

Than Im assigning this empty object to those 2 public variables from Above.

in

void Start()
{
 objectScript = object.GetComponent <NameOfTheReferanceScript> ();
}

Than with this new created object “ObjectScript” i can get all what I wont from NameOfTheReferanceScript scrip.

And you can get it by - objectScript. … whatyou want.