I use the same function in most of my scripts. Is there a way to make it so that I have access to that function without copy/pasting it into every script?
Use the static keyword for your function, which will make it’s use similar to built-in functions. Then you can just call the function from any other script.
This code needs only to be written once:
static function myFunction() { <code> }
Then you can call the function from any other script:
if(conditions met) { myFunction(); }
You can also declare variables for the specific use of the function itself:
static function myFunction (myString:string, myInt:int){ <code> }
Then pass variables into that function when calling it:
if (conditions met) { myFunction("Hello World", 5); }
Thanks for the reply. It seems like your method would work but I’m getting an error of “Unknown identifier: ‘myFunction’.” after creating the static function in one script and trying to call it in another (using the start function).
Edit: Ah figured it out, I needed to put scriptName.myFunction to call it from a separate script. I’m using javascript btw, not sure if it’s different in c#.
Not sure, I’ve only dabbled with C#. But so far as I can tell, the two are really similar. I know this technique can be used in C#, though.
You didn’t mention if you were programming in C# or UnityScript / Javascript.
Either way, what you want is referred to as a Utility class.
Here’s a Stack Overflow topic discussing these:
http://stackoverflow.com/questions/2857832/creating-an-utilities-class
Here’s a simple example using C#. (UnityScript is just as simple, I just don’t have any sample code)
Place your utility class into it’s own class file (and namespace), for example: (Utility.cs)
namespace Utility {
static class Converter {
public static int StringToInt(string value) {
int number;
if (int.TryParse(value, out number))
return number;
else
return 0;
}
}
}
Then to use the utility class, add the reference at the top of your code file, such as:
using Utility;And to call the desired function, you use:
int age = Converter.StringToFloat("24");