数据传值技术可以在不同的脚本之间进行数据传输,目前我在项目中最常使用的传值技术是脚本组件传值技术,这种技术的缺陷就是耦合性大,当更改了某个脚本名称的时候,其他脚本可能也需要做关联性的改变,本节介绍其他数据传值方法:
1.脚本组件传值方法
2.类静态字段传值方法
3.SendMessage数据传值技术
4.定义委托与事件进行数据传值
5.PlayerPrefs技术
6.XML数据持久化技术
7.网络服务器端技术
SendMessage传值技术
实例1
//send.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SendMessage : MonoBehaviour {
public GameObject GoReceiveObj;
// Use this for initialization
void Start () {
GoReceiveObj.SendMessage("DisplayInfoA");
GoReceiveObj.SendMessage("DisplayInfoB");
GoReceiveObj.SendMessage("DisplayInfo2", "good morning");
System.Object[] objs = new System.Object[3];
objs[0] = "大家好";
objs[1] = 1;
objs[2] = 33.33f;
GoReceiveObj.SendMessage("DisplayInfo3",objs);
}
}
//receive.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class receive : MonoBehaviour {
public void DisplayInfoA() {
print(GetType() + "DisplayInfoA");
}
public void DisplayInfoB() {
print(GetType() + "DisplayInfoB");
}
public void DisplayInfo2(string str) {
print(GetType() + str);
}
public void DisplayInfo3(System.Object[] objs)
{
print(GetType() + objs[0].ToString());
print(GetType() + objs[1].ToString());
print(GetType() + objs[2].ToString());
}
}
示例2
SendMessage向下广播发送(BroadcastMessage)和向上广播发送(SendMessageUpwards)
建立三个空对象
//Send挂载脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SendBroadC : MonoBehaviour {
public GameObject obj;
// Use this for initialization
void Start () {
obj.BroadcastMessage("DisplayInfo"); //ONE
// obj.SendMessageUpwards("DisplayInfo");//TWO
}
}
//father挂载脚本
public class fsnd : MonoBehaviour {
public void DisplayInfo() {
print("Father");
}
}
//child挂在脚本
public class childend : MonoBehaviour {
public void DisplayInfo()
{
print("Child");
}
}
首先将send.cs中TWO行注释,将Father对象赋值给Send.cs中的obj,此时打印:
Father
Child
然后,将send.cs中ONE行注释,将child对象赋值给Send.cs中的obj,此时打印:
Child
Father