观察者模式和代理模式

观察者模式:

using UnityEngine;
using System.Collections;

//观察者模式,不断询问程序是否完成了任务
//比如这里我们想要在动画播放1.5秒后发出一个粒子特效,我们在播放动画后就在Update函数中
//不断询问是否到了1.5秒
public class TestObeserve : MonoBehaviour {

	public Animation player;
	float count;//计时器
	void Start () {
		player = GameObject.FindGameObjectWithTag("cube").GetComponent();
	}
	void PlayAnimation(){
		count = 0f;
		player.Play();
		Debug.Log("Animation Play!");
	}
	bool PlayFinish(){
		return player.isPlaying;
	}	
	void PlayPartical(){
		Debug.Log("Play Partical!");
	}
	void Update () {
		if (Input.GetKey(KeyCode.A)){
			PlayAnimation();
		}
		if (!PlayFinish()){
			Debug.Log ("正在执行");
			count += Time.deltaTime;//计数器加上每帧的时间
			if (count >= 0.5f){
				PlayPartical();
			}
		}

	}
}
代理模式:

让对象完成任务后自己报告,使用观察者模式,如果我们播放的动画一多,就要用多个计数器,会使代码混乱,此时使用代理模式,让对象主动报告,做完回调。

using UnityEngine;
using System.Collections;

public delegate void PlayPartical();
public class AnimationDelegate{
	PlayPartical play;
	float count = 0f;
	Animation player;
	public AnimationDelegate(PlayPartical f){
		play = f;
	}
	public void PlayAnimation(){
		count = 0;
		player.Play();
	}
	bool IsPlaying(){
		return player.isPlaying;
	}
	void Update(){
		if (Input.GetKey(KeyCode.A)){
			PlayAnimation();
			if (!IsPlaying()){
				count += Time.deltaTime;
				if (count >= 1.5f){
					play();
				}
			}
		}
	}

}

public class TestDelegate : MonoBehaviour {
	//播放10个动画
	AnimationDelegate[] a = new AnimationDelegate(PlayPartical)[10];
	public void PlayPartical(){
		Debug.Log("Play Partical!");
	}

	void Start () {
		for (int i=0; i<10; i++){
			a[i].PlayAnimation();
		}
	}
	
	void Update () {

	}
}



你可能感兴趣的:(Unity3d)