`
berry_gong
  • 浏览: 5078 次
  • 性别: Icon_minigender_2
  • 来自: 厦门
最近访客 更多访客>>
社区版块
存档分类
最新评论

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;
    }
  }
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics