Skip to content

Instantly share code, notes, and snippets.

@Bradshaw
Created July 18, 2018 17:26
Show Gist options
  • Save Bradshaw/ee93ab40ede9c4077153068de502c5b7 to your computer and use it in GitHub Desktop.
Save Bradshaw/ee93ab40ede9c4077153068de502c5b7 to your computer and use it in GitHub Desktop.
Little delegate example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// This is what our events look like
public delegate void AimTrackerEvent(Vector3 point, int playerNumber);
public class AimTracker : MonoBehaviour {
// These are all the events
public static AimTrackerEvent OnTrackerMove;
public static AimTrackerEvent OnTrackerClick;
// Update is called once per frame
void Update () {
float hori1 = Input.GetAxis("joystick 1 analog 0");
float vert1 = Input.GetAxis("joystick 1 analog 1");
float hori2 = Input.GetAxis("joystick 2 analog 0");
float vert2 = Input.GetAxis("joystick 2 analog 1");
// CLEAN
// If someone is listening
if (OnTrackerMove!=null){
// Broadcast our message
OnTrackerMove(new Vector3(hori1, vert1, 0), 1);
OnTrackerMove(new Vector3(hori2, vert2, 0), 2);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrackerPoint : MonoBehaviour {
public int player;
// Use this for initialization
void Start () {
// Listen for Tracker Move events
AimTracker.OnTrackerMove += MoveMe;
}
// CLEAN!
void OnDestroy(){
// We're dead, stop listening for Tracker Move events
AimTracker.OnTrackerMove -= MoveMe;
}
// This has the same signature as "AimTrackerEvent" in the AimTracker.cs file
// So we can use it to listen for AimTrackerEvent broadcasts
// void Vector3 int
// vvvv vvvvvvv vvv
void MoveMe(Vector3 p, int pnum){
if (pnum == this.player){
Debug.Log(p);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment