I use a script called ObjectInfo on items in my game, is it possible to access a variable from those gameobjects without making it static?
I know you can use var Examplevar : ExampleScript;
but doesn’t that just make you attach a gameobject, not a script?
Hope this helps:
using System;
using UnityEngine;
class Script_A : MonoBehaviour
{
public int hps = 10;
}
class Script_B : MonoBehaviour
{
private Script_A data_script;
void Start()
{
//If this script is on the same GameObject as Script_A:
data_script = GetComponent<Script_A>();
print("Script A has " + data_script.hps + " HPs left!");
//The above is the same as saying:
data_script = this.GetComponent<Script_A>();
//if this script is NOT on the same GameObject as Script_A,
//and there is only one instance of Script_A:
data_script = (Script_A) FindObjectOfType(typeof(Script_A));
print("Script A has " + data_script.hps + " HPs left!");
//If you have many instances of Scrip_A (like you would if
//it keeps track of HPs), you need to get a hold of the script
//that belongs to the Gameobject you need info on.
//Use the first example by calling GetCompenonet on the object:
data_script = SomeGameObject.GetComponent<Script_A>();
print("Script A has " + data_script.hps + " HPs left!");
}
}