I know there are other forums that somewhat explain this but could anyone tell be is there a way to call a function in another script without an instance of it running? (It’s an editor script with parameters) Also I heard making it ‘static’ or ‘global’ is a possiblity, I’d also like an explaination as well, but I have no I idea. I’d appreicated some help.
you need an instance of an object to call a member of it (method, property, or field).
static members can be accessed on the class, but static members themselves also can only access the static members of itself. It too would have to instantiate an instance of itself to access any non-static implementation with-in itself.
it’s called Singleton: Sample C#
using UnityEngine;
using System.Collections;
public class SingletonTest : MonoBehaviour
{
public static SingletonTest Instance;
void Awake()
{
Instance = this;
}
public void Message(string message)
{
print("message: " + message);
}
}
Another script class (it can be attached to another game object)
using UnityEngine;
using System.Collections;
public class AnotherClass : MonoBehaviour
{
void Update()
{
SingletonTest.Instance.Message("Hello there: " + Time.deltaTime);
}
}
Singleton is yet another answer.
But technically OP asked for “without an instance of it running”, and a Singleton creates an Instance of it. Especially in the case of your MonoBehaviour, which means it had to of been added to a GameObject somewhere… so to access it, not only do you have to create an instance of it, but you have to create a GameObject for it.
OP, what are you trying to create? A utility class or something? Why is it this function needs to be accessed with out an instance of it? Are you trying to create a class that holds several functions for utility purposes. This is called a ‘static utility class’, see here:
It would depend on the solution he is trying to find, but both ideas can be used.
Knowing the way he can decide wich way is the best for his problem.
![]()
Okay, I was trying to see if I could. There was a way you could do it but I don’t remember. I use java btw but there was a way I saw:
//the script in project, not in scene, Script A
static function functionName (multiple arguements){
//...do stuff
}
//and a script in scene, Script B
function Start () {
ScriptA.functionName(parameters);
}
ADDED: Also how would I call a member of it?
that’s a static function
That’s what I though but I get an error is the process. “Unknown identifer: ‘Save’.” Save is the name of the script(ScriptA in this scenario).
this means the class can’t be located, as opposed to the function.
This usually happens because it isn’t compiling, or compiled after the script that you’re trying to access it from.
Consider the compilation order:
http://docs.unity3d.com/Documentation/ScriptReference/index.Script_compilation_28Advanced29.html
Oh okay, The editor files is compiled last making error is what I can presume so the script can’t really find it.