Hey Im pretty new to the unity scene, I’ve been trying to figure out how I could do something similar to C++'s #include on a script and simply call on any function in that script, I’ve seen the mass of posts saying use getComponent but isn’t there a more efficient way? I’m going to be accessing the same scripts over and over from many different sources
IE:
#include ScriptB
Start()
{
ScriptB.ChangeTime(5); // → Changes time variable in ScriptB using a public function
}
I am not a C/C++ expert, but AFAIK, #include
just tells the preprocessor to copy-paste a given fine into the current file.
The libraries you include this way ( cstdio
, cstring
, …) define functions that does not need an instance of a class. They just need the variables you give to them. We could see this as global static functions.
What you are trying to do won’t work, simply because ScriptB.ChangeTime(5)
needs an instance of a class ( ScriptB
), and you have to provide this reference somehow… Or maybe, ChangeTime
is a staic function, and in this case, you don’t need to do anything more but calling the function this way (without anything else, no include)
To provide the instance of the ScriptB
class, I can be difficult to provide a universal way. It really depends on your project (where is attached the script, its lifecycle, etc). You may be able to simplify your calls using extension methods but I don’t think it will be worth it in the end…
If you need the script to be attached on the current object
public static class ScriptBExtensions
{
public static ScriptB GetScriptB(this MonoBehaviour monoBehaviour)
{
ScriptB B = monoBehaviour.GetComponent<ScriptB>();
if (B == null)
B = monoBehaviour.gameObject.AddComponent<ScriptB>();
return B;
}
}
And you call it:
void Start()
{
GetScriptB().ChangeTime(5);
}
If you know there is only one instance of the script the scene
public static class ScriptBExtensions
{
public static ScriptB GetScriptB(this MonoBehaviour monoBehaviour)
{
return FindObjectOfType<ScriptB>();
}
}