Unity单例和事件

 

 

继承自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;
    }
  }
}

 

 

 

你可能感兴趣的:(unity)