Unity中游戏体的消息传递

Unity中游戏体的消息传递

SendMassage

void function SendMessage (methodName : string, value : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver)  


向同级发送消息

在这个游戏物体上的所有MonoBehaviour上调用名称为methodName的方法。


也就是说如果某个游戏体调用这个方法就会调用所有这个游戏体脚本中名字为methodname的函数

需要注意的是这个游戏体的Child不会调用名字为methodname的函数

假如有某个游戏体有两个脚本组件

Eng.cs

using System.Collections;

public class Eng : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void Speak()
    {
        Debug.Log(" I can speak Eng !!!");
    }
}

Chinese.cs

using UnityEngine;
using System.Collections;

public class Chinese : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void Speak()
    {
        Debug.Log(" 我会说中文 !!!");
    }
}

当这个游戏体调用SendMassage时候

Chinese.cs 和 Eng.cs中的Speak()函数都会被执行

Unity中游戏体的消息传递_第1张图片


BroadcastMessage

void  function BroadcastMessage (methodName : string, parameter : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver) 


朝物体和所有子物体发送消息。

假设有个Grandpa的游戏体,上面有个Father,Father上面有个Child



Grandpa.cs
using System.Collections;

public class Grandpa : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void Speak()
    {
        Debug.Log(" Im Grandpa !!!");

    }
}

Father.cs
using UnityEngine;
using System.Collections;

public class Father : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void Speak()
    {
        Debug.Log(" Im Father !!!");
    }
}

Child.cs
using UnityEngine;
using System.Collections;

public class Child : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void Speak()
    {
        Debug.Log(" Im Child !!!");
    }
}

当Grandpa游戏体执行BroadCastMessage()函数的时候
Grandpa本身包括其所有的子物体脚本组件都会执行methodname函数
Unity中游戏体的消息传递_第2张图片

SendMessageUpwards 

void function SendMessageUpwards (methodName : string, value : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver) 

朝物体和上级父物体发送信息


如果Father游戏体调用SendMessageUpwards ().只有它本身和所有他的父节点会执行Methodname函数


Unity中游戏体的消息传递_第3张图片



你可能感兴趣的:(Unity基础)