J K
J K

Reputation: 642

How do I make global event in unity3?

I am making tour-based game in unity.
I would like to have in (almost)all my classes a function OnNextRound,
which will be called when user clicks 'next round' button.

void OnGUI() {
    // ...

    if (GUI.Button(new Rect(10f, Screen.height - 40, 100, 30), "next round")) {
        // here call all OnNextRound functions
    }
}

Some of classes that also have to contain this OnNextRound function aren't extending MonoBehaviour:

public class SomeClass {
    // some vars and functions here
}

And instantiaded by this way:

SomeClass sc = new SomeClass(/* some params */);

These classes also have to contain OnNextRound function.

So, I want to call all functions named OnNextRound in every instance of every class.

How to make this, or maybe it's impossible to do it this way? If it's impossible, so how can I reach similar effect?

I am new to C#, however I have experience in other languages.

Upvotes: 1

Views: 1963

Answers (2)

Galandil
Galandil

Reputation: 4249

Just use a simple event.

using UnityEngine;
using System;

public class EventExample : MonoBehaviour {

    public static event Action myEvent;

    void OnGUI() {
        if (GUI.Button(new Rect(10f, Screen.height - 40, 100, 30), "next round")) {
            myEvent();
        }
    }
}

Then, in all scripts where you want to call your OnNextRound() method, add these lines:

private void Awake() {
    EventExample.myEvent += OnNextRound;
}

private void OnNextRound() {
    //Do your stuff
}

Anyway, a couple of words:

  • Don't use OnGUI, use an UI Button
  • The signature of the event must match the signature of the OnNextRound method. If for example your method requires a string parameter, then the event should be declared as an Action<string>. If your method has a return type, then you should use Func instead of Action (you can read in depth about Action and Func delegates on the Microsoft C# knowledge base site).

Edit: Since you added the bit about a non MonoBehaviour class, you can register your method to the EventExample.myEvent in the constructor of the class, i.e.:

public class SomeClass {

    public SomeClass () {
        EventExample.myEvent += OnNextRound;
    }

    private void OnNextRound() {
        //Do stuff
    }
}

Upvotes: 2

Zyzz Shembesh
Zyzz Shembesh

Reputation: 220

You can simply make a class called onNextRound then inside it delete the star() and update functions and create onNextRound () and then write your functions. MAKE IT PUBLIC

now attach this script to your main camera.

finally you can create and instance of this class inside any class you need and call that function

Upvotes: 1

Related Questions