Referencing different scripts is actually quite easy - but can get confusing if you don’t have a proper hierarchy and setup. Below I will discus methods and strategies to reference other scripts.
Method 1: Scripts on the Same Object
This is the easiest on to do. If you have to scripts on the same Transform/Object you can reference it with GetComponent<>(). For example you have two scripts on an object, InventoryItemsDatabase and InventoryControll.
You want to access InventoryItemsDatabase from the InventoryControll script. It will look like this
public class InventoryControll : MonoBehaviour {
// Variable to store script so we
// don't have to use GetComponent every time.
InventoryItemsDatabase itemDB;
// Assign in on Start
void Start () {
itemDB = GetComponent<InventoryItemsDatabase>();
}
// Usage Example
void RemoveItem (int id){
itemDB.Remove(id);
}
}
Method 2: Referencing Objects from Parent Or Root
Say you have an hierarchy structure of objects
-> GameManager {Root Object}
--> PlayerManager
--> AIManager
--> InventoryManager [InventoryManager, InventoryDatabase] {Parent Object to InventoryControll}
---> InventoryControll [InventoryControll]
Here we have the InventoryControll on a separate object that is a child if the InventoryManager object which contains two scripts, InventoryManager and InventoryDatabase.
If we want to access the InventoryDatabase we can use the following code:
// Assign in on Start
void Start () {
// Using GetComponent
itemDB = transform.parent.GetComponent<InventoryItemsDatabase>();
// Using GetComponentInParent
itemDB = GetComponentInParent<InventoryItemsDatabase>();
}
Similar if the object was in the root (The most top parent you can get) you can use the code:
transform.root.GetComponent<InventoryItemsDatabase>()
Method 3: Drop and Drag for non hierarchy structures
Another way to do it is to add a reference to the object, drop and drag that object onto a variable. Create a public variable as a Transform.
public Transform InventoryDatabaseTransform;
This variable will now be visible in the inspector. Simply while you have the InventoryControll object select in the hierarchy (so we can see the above variable in the inspector), click and drag the InventoryDatabase object from the inspector to the variable in the inspector.
You should now be able to use getcomponent in the InventoryControll script as such:
void Start () {
itemDB = InventoryDatabaseTransform.GetComponent<InventoryDatabase> ();
}
Hope this helped. Just comment if you have further issues.
Method 4: SearchObject
Simply search for the object you want by name:
void Start () {
itemDB = GameObject.Find("InventoryDatabase").GetComponent<InventoryDatabase>();
}
I hope this helped you out!