Quantcast
Channel: Unity - Live Training Archive
Viewing all articles
Browse latest Browse all 12

Events: Creating a simple messaging system

$
0
0

Download the project audio files (including Character Scream and Pop sounds) HERE.

EventManager

Code snippet

using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;

public class EventManager : MonoBehaviour {

    private Dictionary <string, UnityEvent> eventDictionary;

    private static EventManager eventManager;

    public static EventManager instance
    {
        get
        {
            if (!eventManager)
            {
                eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;

                if (!eventManager)
                {
                    Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
                }
                else
                {
                    eventManager.Init (); 
                }
            }

            return eventManager;
        }
    }

    void Init ()
    {
        if (eventDictionary == null)
        {
            eventDictionary = new Dictionary<string, UnityEvent>();
        }
    }

    public static void StartListening (string eventName, UnityAction listener)
    {
        UnityEvent thisEvent = null;
        if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.AddListener (listener);
        } 
        else
        {
            thisEvent = new UnityEvent ();
            thisEvent.AddListener (listener);
            instance.eventDictionary.Add (eventName, thisEvent);
        }
    }

    public static void StopListening (string eventName, UnityAction listener)
    {
        if (eventManager == null) return;
        UnityEvent thisEvent = null;
        if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.RemoveListener (listener);
        }
    }

    public static void TriggerEvent (string eventName)
    {
        UnityEvent thisEvent = null;
        if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.Invoke ();
        }
    }
}

EventTest

Code snippet

using UnityEngine;
using UnityEngine.Events;
using System.Collections;

public class EventTest : MonoBehaviour {

    private UnityAction someListener;

    void Awake ()
    {
        someListener = new UnityAction (SomeFunction);
    }

    void OnEnable ()
    {
        EventManager.StartListening ("test", someListener);
        EventManager.StartListening ("Spawn", SomeOtherFunction);
        EventManager.StartListening ("Destroy", SomeThirdFunction);
    }

    void OnDisable ()
    {
        EventManager.StopListening ("test", someListener);
        EventManager.StopListening ("Spawn", SomeOtherFunction);
        EventManager.StopListening ("Destroy", SomeThirdFunction);
    }

    void SomeFunction ()
    {
        Debug.Log ("Some Function was called!");
    }
    
    void SomeOtherFunction ()
    {
        Debug.Log ("Some Other Function was called!");
    }
    
    void SomeThirdFunction ()
    {
        Debug.Log ("Some Third Function was called!");
    }
}

EventTriggerTest

Code snippet

using UnityEngine;
using System.Collections;

public class EventTriggerTest : MonoBehaviour {


    void Update () {
        if (Input.GetKeyDown ("q"))
        {
            EventManager.TriggerEvent ("test");
        }

        if (Input.GetKeyDown ("o"))
        {
            EventManager.TriggerEvent ("Spawn");
        }

        if (Input.GetKeyDown ("p"))
        {
            EventManager.TriggerEvent ("Destroy");
        }

        if (Input.GetKeyDown ("x"))
        {
            EventManager.TriggerEvent ("Junk");
        }
    }
}

DestroyByTimeExtended

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyByTimeExtended : MonoBehaviour {

    public float lifeTime;
    // Use this for initialization
    void Start () {
        Destroy (gameObject, lifeTime);
        GetComponent <AudioSource>().pitch = Random.Range (0.75f, 1.25f);
    }
}

SelfDestruct

Code snippet

using UnityEngine;
using UnityEngine.Events;
using System.Collections;

public class SelfDestruct : MonoBehaviour {

    public GameObject explosion;

    private float shake = 0.2f;
    private AudioSource audioSource;
        
    void Awake () 
    {
        audioSource = GetComponent <AudioSource>();
    }
    
    void OnEnable () 
    {
        EventManager.StartListening ("Destroy", Destroy);
    }
    
    void OnDisable () 
    {
        EventManager.StopListening ("Destroy", Destroy);
    }
    
    void Destroy () 
    {
        EventManager.StopListening ("Destroy", Destroy);
        StartCoroutine (DestroyNow());
    }

    IEnumerator DestroyNow() 
    {
        yield return new WaitForSeconds (Random.Range (0.0f, 1.0f));
        audioSource.pitch = Random.Range (0.75f, 1.75f);
        audioSource.Play ();
        float startTime = 0;
        float shakeTime = Random.Range (1.0f, 3.0f);
        while (startTime < shakeTime) 
        {
            transform.Translate (Random.Range (-shake, shake), 0.0f, Random.Range (-shake, shake));
            transform.Rotate ( 0.0f, Random.Range (-shake * 100, shake * 100), 0.0f);
            startTime += Time.deltaTime;
            yield return null;
        }
        Instantiate (explosion, transform.position, transform.rotation);
        Destroy (gameObject);
    }
}

Spawner

Code snippet

using UnityEngine;
using UnityEngine.Events;
using System.Collections;

public class Spawner : MonoBehaviour {

    public int spawnCount;
    [Range (1,100)]
    public int spawnSize = 1;
    public float minionOffset = 1;
    public GameObject minion;

//  private UnityAction spawnListener;
//
//  void Awake () {
//      spawnListener = new UnityAction (Spawn);
//  }

    void OnEnable () {
//      EventManager.StartListening ("Spawn", spawnListener);
        EventManager.StartListening ("Spawn", Spawn);
    }

    void OnDisable () {
//      EventManager.StopListening ("Spawn", spawnListener);
        EventManager.StopListening ("Spawn", Spawn);
    }

    void Spawn () {
        for (int i = 0; i < spawnCount; i++) {
            Vector3 spawnPosition = GetSpawnPosition ();

            Quaternion spawnRotation = new Quaternion ();
            spawnRotation.eulerAngles = new Vector3 (0.0f, Random.Range (0.0f, 360.0f));
            if (spawnPosition != Vector3.zero) {
                Instantiate (minion, spawnPosition, spawnRotation);
            }
        }
    }

    Vector3 GetSpawnPosition () {
        Vector3 spawnPosition = new Vector3 ();
        float startTime = Time.realtimeSinceStartup;
        bool test = false;
        while (test == false) {
            Vector2 spawnPositionRaw = Random.insideUnitCircle * spawnSize;
            spawnPosition = new Vector3 (spawnPositionRaw.x, minionOffset, spawnPositionRaw.y);
            test = !Physics.CheckSphere (spawnPosition, 0.75f);
            if (Time.realtimeSinceStartup - startTime > 0.5f) {
                Debug.Log ("Time out placing Minion!");
                return Vector3.zero;
            }
        }
        return spawnPosition;
    }
}
Undefined
Sort Order: 
14
Unity Version: 
5.00
Type: 
Lesson
Difficulty: 
Intermediate

Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>