1. 程式人生 > >Unity3D 利用C#實現簡單的代理模式Delegate(委託)

Unity3D 利用C#實現簡單的代理模式Delegate(委託)

Ref: http://www.cnblogs.com/shadow7/p/5892641.html

1、Delegate是什麼?

Delegate中文翻譯為“委託”。
C#語言是支援代理的,並且代理是非常的好用的一種方式。簡單的來說就是你委託別人幫你做一件事情,當委託人做完你委託的事情之後會告訴你他做完了。C#中的委託類似於C或C++中的函式指標。使用委託使程式設計師可以將方法引用封裝在委託物件內。然後可以將該委託物件傳遞給可呼叫所引用方法的程式碼,而不必在編譯時知道將呼叫哪個方法。與C或C++中的函式指標不同,委託是面向物件、型別安全的,並且是安全的。

先簡單的使用一下Delegate(委託)

直接程式碼:

代理的宣告,在開發中應該有一個專門用來委託的類。

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

public class CubeManager : MonoBehaviour {

    delegate void CubeMoveHDelegate();      // //委託的識別符號就是delegate,LogMessageDelegate(string message)就是委託完畢後回撥的方法名稱 
    CubeMoveHDelegate hDelegate;

	// Use this for initialization
	void Start () {
        SmartCube[] cubes = FindObjectsOfType(typeof(SmartCube)) as SmartCube[];
        for(int i = 0; i< cubes.Length; i++) {
            SmartCube c = cubes[i];
            hDelegate += c.MoveHorizontal;
        }
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow)) {
            hDelegate();
        }
	}
}


使用代理,需要把具體的實現類方法 掛載到相關的gameobject上。

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

public class SmartCube : MonoBehaviour {

    public float speed = 10;

	public void MoveHorizontal() {
        transform.Translate(Time.deltaTime * speed * Input.GetAxis("Horizontal"), 0, 0);
    }

}