- Home /
Static function won't call another static function
If I try doing this:
static function f() {
go();
}
static function go() {
yield;
}
I will get an error saying:
UCW0004: WARNING: Coroutine 'go' cannot be automatically started from a static function.
Why can I not do this? The function will not even run, and my real code really needs to use a static function in a static function.
Answer by KellyThomas · Dec 30, 2013 at 04:18 PM
I think Unity coroutines need to be attached to a GameObject.
You will have no trouble calling static (non-coroutine) functions from static functions.
You can replace yield
with a log statement for a simple test.
Yeah, I just tried with a log, and it did work, but what do you mean by attaching a coroutine to a GameObject?
I'm having trouble find a reference (someone else might have a good link) but the unity coroutines are very closely tied to GameObjects (i.e. they can't be started if their game object is inactive, they stop when the game object is set to inactive or destroyed). As such they are tied to that instance and can't be static functions.
Well yeah, all of the $$anonymous$$onoBehaviour message functions are designed to apply to a single GameObject instance.
Okay, I might sound like an idiot right here, but what should my solution be then? I'll give you a sample of my real code.
static function PlaySound(obj:GameObject,x:AudioClip){
var source = obj.AddComponent(AudioSource);
source.clip = x;
source.Play();
while(source){
if(!source.isPlaying){
Destroy(source);
}
yield;
}
}
static function Damage(amount:int,rig:Rigidbody2D,properties:Properties,pileUp:float,sounds:AudioClip[],sound1:int,sound2:int){
properties.health -= amount;
rig.velocity = new Vector2(rig.velocity.x,0);
rig.AddForce(Vector3(2,2,0)*200/rig.mass);
PlaySound(rig.gameObject,sounds[sound1]); //I need to play a sound using the static function from above
PlaySound(rig.gameObject,sounds[sound2]);
Invincible(0.5,properties,rig.gameObject,true,pileUp,0); //Not going to focus on this one for now, even though this is also a problem
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613125143im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Attempt to insert 9Slice RenderData twice warning in erroneous places 0 Answers
SendMessage cannot be called during Awake, CheckConsistency, or OnValidate 0 Answers
"Failed to call static function because an object was provided" error? 1 Answer
error CS0649 1 Answer
Saving and Loading with a static or a local function 0 Answers