- Home /
How do I access a static function in JS?
At least that's what I think I want. Really , I want to be able to access a function without the need to attach my script (in which the function is defined) to a Game Object.
In my scenario I want an audio manager class to be accessed from multiple scripts within my project without the need to create an Audio Manager gameobject and then do a GameObject.Find...etc in every script.
Now I thought this should be pretty straightforward form all the examples I read but I just get errors. I have tried creating the following script:
public class audio_manager
{
function PlayAudio()
{
//do stuff
}
}
..and then in another script doing audio_manager.PlayAudio(); but this doesn't work. So what is the simplest way to access this function?
P.S> I read many attempts to explain this with Singletons and C# but non of those examples are simple enough for my small mind. Shortest correct answer wins ;)
Thanks!
Answer by ArkaneX · Nov 15, 2013 at 01:50 PM
static function PlayAudio()
EDIT: answer was short as you requested, but I decided to expand it a bit :)
Marking a method as static means not only availability to access it without creating instance of your class. It also means, that you can't access any instance methods or variables withing your script. So remember that static is not appropriate in all the cases.
Uh - it seems I was editing the answer while you accepted, but please read the update.
Gotcha, although I'm not sure if I can accept that now. It's far too long ;) Thanks Again!
On another related note, how can I create a new GameObject from within this class at runtime? In the class's Awake function I do AudioStoreObject =new GameObject("AudioStore");
but nothing is created at runtime.
Nothing is created, because Awake is called only for scripts extending $$anonymous$$onoBehaviour, and attached to a game object. Original script from your answer does not extend $$anonymous$$onoBehaviour.
Your answer
Follow this Question
Related Questions
Using static constants from an outside script 2 Answers
Field is never assigned to and will always have its default value. 0 Answers
How to access variables from other scripts without static (javascript) 1 Answer
Field is never assigned to, and will always have its default value 3 Answers
Static array with custom class? 1 Answer