Unityの一例とイベント
2135 ワード
Monoから継承された単一の書き方:
public class Clicker : MonoBehaviour
{
// Singleton
private static Clicker instance;
// Construct
private Clicker() {}
// Instance
public static Clicker Instance
{
get
{
if (instance == null)
instance = GameObject.FindObjectOfType(typeof(Clicker)) as Clicker;
return instance;
}
// Do something here, make sure this is public so we can access it through our Instance.
public void DoSomething() { }
...
管理、およびトリガーされたときの応答を定義します.
public class Clicker : MonoBehaviour
{
// Event Handler
public delegate void OnClickEvent(GameObject g);
public event OnClickEvent OnClick;
// Handle our Ray and Hit
void Update ()
{
// Ray
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
// Raycast Hit
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
// If we click it
if (Input.GetMouseButtonUp(0))
{
// Notify of the event!
OnClick(hit.transform.gameObject);
}
}
}
}
その他のオブジェクトによるリスニングの追加
public class GoldPile : MonoBehaviour
{
// Awake
void Awake ()
{
// Start the event listener
Clicker.Instance.OnClick += OnClick;
}
// The event that gets called
void OnClick(GameObject g)
{
// If g is THIS gameObject
if (g == gameObject)
{
Debug.Log("Hide and give us money!");
// Hide
gameObject.active = false;
}
}
}