一:用代码生成多个组件,一般可以是一排按钮,一排文本等等:
- 新建一个prefabs,放在Resources文件夹待用,再组件中产生一个空组件作为父组件,这样可以保持整洁,代码如下:
Transform buttonParent = transform.Find("/Canvas/button");//按钮的父目录
Button button_prefabs = Resources.Load<Button>("Button_pfb");//获取到按钮的预制体
for (int i = 0; i < 12; i++)
{
button[i] = Instantiate(button_prefabs, buttonParent);
int index = i; //这个非常重要,传递的参数不能是i
button[i].GetComponent<Button>().onClick.AddListener(delegate
{
button_click(index);//这个非常重要,传递的参数不能是i
});
button[i].transform.localPosition = new Vector3((i) % 3 * 350 - 350, 500- (i) / 3 * 200, 0); //放的位置,可以是多排的方阵
button[i].name = "button_" + i;//组件名字
button[i].GetComponentInChildren<Text>().text = (i).ToString();//按钮显示的名字
}
2.按钮按了以后的处理部分程序:
private void button_click(int index)
{
print("button_click" + index);
//这里写实际的代码
}
二:常用文件夹
Scenes:一般只存放场景
Prefabs:预设物文件夹
Audio:存放音频文件
Material:存放材质文件
Image/UI/Sprite/Textrue:都属于贴图类资源,其中sprite用于开发2d游戏中的精灵贴图
Scripts:存放脚本文件
Plugins:
Resources:资源,图片,视频等
StreamingAssets:
这个文件夹下的资源也会全都打包在.apk或者.ipa 它和Resources的区别是,Resources会压缩文件,但是它不会压缩原封不动的打包进去。并且它是一个只读的文件夹,就是程序运行时只能读 不能写。它在各个平台下的路径是不同的,不过你可以用Application.streamingAssetsPath 它会根据当前的平台选择对应的路径。发现也可以写入文件。
System.DateTime now = new System.DateTime();
now = System.DateTime.Now;
string timestr = now.ToString("MMdd_hhmmss");
//string filename = string.Format("image{0}{1}{2}{3}.png", now.Day, now.Hour, now.Minute, now.Second);
string filename = "image" + timestr + ".png";
//把图片转成PNG格式
byte[] bytes_save = texture.EncodeToPNG();
//写一下你打算保存到哪
string s = Application.streamingAssetsPath + "/" + filename;
//最后把转换好的格式,保存在你想保存的地址里
System.IO.File.WriteAllBytes(s, bytes_save);
三:多屏显示的代码:
private void Awake()
{
if (Display.displays.Length > 1)
{
for (int i = 0; i < Display.displays.Length; i++)
{
Display.displays[i].Activate();
}
}
}
四:退出程序的代码:
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
五:退出线程的代码:
退出程序的时候不知道后台线程不退会不会有什么不好,所以还是退一下安全点:
先是这个代码,程序退出后:
private void OnDestroy()
{
//关闭通讯线程
isend = true; //如果退出就关闭线程
}
再是在线程的循环增加判断:
if (isend) //如果退出就关闭线程
break;
跳出循环后:
print("退出就关闭线程 state: " + th.ThreadState); //如果退出就关闭线程
if (th.ThreadState == System.Threading.ThreadState.Running)
{
print("接收线程关闭!");
th.Abort(); //如果退出就关闭线程
}
六:多个组件代码之间的数据传递:
PlayerPrefs.SetInt(“intKey”, 1234); //发送方用这个发数据
int intVal = PlayerPrefs.GetInt(“intKey”);//接收方用这句代码接收数据
这个虽然很简单,有个缺点,就是接收方要主动去查看数据,因为他不知道什么时候数据过来了。
七:数据传递:
发送方:
GameObject.Find(“/Canvas/Text_value”).GetComponent().SendMessage(“get_message”, “87654321”);
发送方必须知道接收方的所在的组件,找到组件后用获取getmessage(接收方的:public class getmessage : MonoBehaviour),再发送给它对应的方法get_message,以及发送的数据“87654321”;
接收方:
public void get_message(string str)
{
text_str.text = str;
}
这个方法有一点点麻烦,好处是接收方不需要等待数据的到来,到了自然就执行的对应的方法,可以即可获得需要的效果。比较推荐这个方法。
太晚了,先写这么多了,希望对你有所帮助。