实现游戏对象之间的通信

来源:互联网 发布:大数据性能 编辑:程序博客网 时间:2024/04/30 14:17
游戏中,对象与对象之间需要交流,实现的方法多种,例如:可定义静态变量,其他脚本直接调用, 也可用到: SendMessage

今天主要学习SendMessage的用法。

 

1、创建两个脚本:“Cube0”和“Cube1”;

2、将两个脚本分别拖拽到Cube0和Cube1对象中;

3、修改Main.cs脚本:

 

[csharp] view plaincopy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Main : MonoBehaviour   
  5. {  
  6.       
  7.     //定义全局游戏对象  
  8.     GameObject obj0;  
  9.     GameObject obj1;  
  10.       
  11.     void Start ()  
  12.     {  
  13.         //获取两个游戏对象  
  14.         obj0 = GameObject.Find("Cube0");  
  15.         obj1 = GameObject.Find("Cube1");  
  16.     }  
  17.       
  18.       
  19.       
  20.     void OnGUI()   
  21.     {  
  22.         if(GUILayout.Button("Move0"))  
  23.             {  
  24.                 //告诉Cube0对象,发送一个方法  
  25.                 //Receive是方法名称,My Code是参数;绑定的obj0对象脚本中需要有一个Receive方法接收参数  
  26.                 obj0.SendMessage("ReceiveCube","My Cube0");  
  27.                 obj1.SendMessage("ReceiveCube","My Cube1");  
  28.             }  
  29.           
  30.     }  
  31.   
  32.       
  33.     void Update ()   
  34.     {  
  35.           
  36.     }  
  37. }  

 


设置Cube0 和 Cube1 脚本:

 

Cube0脚本:

[csharp] view plaincopy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Cube0 : MonoBehaviour   
  5. {  
  6.     //ReceiveCube方法,接收Main.cs传过来的参数  
  7.     void ReceiveCube(string str)  
  8.     {  
  9.         Debug.Log(str);  
  10.     }     
  11.       
  12. }  

 

Cube1脚本:

[csharp] view plaincopy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Cube1 : MonoBehaviour   
  5. {  
  6.     //ReceiveCube方法,接收Main.cs传过来的参数  
  7.     void ReceiveCube(string str)  
  8.     {  
  9.         Debug.Log(str);  
  10.     }  
  11.       
  12. }  


效果可见:


原创粉丝点击