2014-09-20 16:46:33 u014678046 阅读数 6076


    在unity3d工程里面StreamingAssets文件夹下面的东西会随着你导出安卓安装包而导出。

根据圣殿上面给出的解释,在安卓里面都保存在在压缩的.jar文件中,这里面的文件不会随着应用的安装解压出来,而是一直存放在里面,。你可以用WWW类去进行

读取。

下面是他的读取路径,小编在工程里面的asset目录下手动创建文件夹StreamingAssets  ,里面存放用到的assetbundle类型的资源包。在安卓手机上面的读取路径如下:

string path = "jar:file://" + Application.dataPath + "!/assets/" + name;

name就是你要读取的资源文件;

通过

WWW mybundle = new WWW (path);
   yield return mybundle ;

上面就可以将你的文件读出,获得数据流mybundle.bytes,这样资源就被都出来了,下面进行写入,写入的方法很简单,通过下面的函数即可,

path是你要将文件写入手机的位置,这要看你的需求,比如可以写到Application.persistentDataPath里面,这就相当于手机的保存数据的地方,就是手机的沙盒文件。

FileInfo t = new FileInfo (path+"//"+name);
  if (!t.Exists) {
   sw = t.Create (); 
  } else {
   print ("已经存在,");
  }
  sw.Write (info,0,length);
  sw.Close ();
  sw.Dispose ();

通过上面的方法就将工程里面的asset目录下手动创建文件夹StreamingAssets  里面名字为name的资源写到了手机本地,为以后的资源更新准备。


2015-05-31 14:17:41 ivebeenready 阅读数 2236

网上有两个常用的方法,我先用了第一种。

第一种方法:

需要注意三点,首先导入system.window.Forms.dll库,导进去后一定记得要修改playersetting下的optimization->API compatibility level为.NET 2.0,至于为什么改成这样,可以参考unity3d 的解释:http://game.ceeger.com/Manual/MobileDotnet.html。

还要注意一点:加载的本地图片地址一定不能带有中文路径

另外,www新建的时候要加上“file://” + url;

WWW www = new WWW("file://" + url);  //注意要加上"file://"

只需要一个脚本,其中代码如下:

using UnityEngine;
using System.Collections;
using System.Windows.Forms;
using System.IO;
public class UploadImg: MonoBehaviour {
	public Texture2D img = null;  
	void OnGUI()  
	{  
		if (GUI.Button(new Rect(0, 0, 100, 20), "选择文件"))  
		{  
			
			OpenFileDialog od = new OpenFileDialog();  
			od.Title = "请选择头像图片";  
			od.Multiselect = false;  
			od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";  
			if (od.ShowDialog() == DialogResult.OK)  
			{  
				Debug.Log(od.FileName);
				StartCoroutine(GetTexture(od.FileName));  

			}  
		}  
		if (img != null)  
		{  
			GUI.DrawTexture(new Rect(0, 20, img.width/2, img.height/2), img);  
		}  
	}  
	
	IEnumerator GetTexture(string url)  
	{  
		WWW www = new WWW("file://" + url);  //注意要加上"file://"
		yield return www;  
		if (www.isDone)  
		{  
			img = www.texture;      
		}  
	}  
}


效果是这样的,但是感觉和win7风格差的太远



第二种方法看起来要炫多了:

需要两个脚本。

OpenFileName.cs如下:

using UnityEngine;  
using System.Collections;  
using System;  
using System.Runtime.InteropServices;  

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]  

public class OpenFileName  
{  
	public int structSize = 0;  
	public IntPtr dlgOwner = IntPtr.Zero;  
	public IntPtr instance = IntPtr.Zero;  
	public String filter = null;  
	public String customFilter = null;  
	public int maxCustFilter = 0;  
	public int filterIndex = 0;  
	public String file = null;  
	public int maxFile = 0;  
	public String fileTitle = null;  
	public int maxFileTitle = 0;  
	public String initialDir = null;  
	public String title = null;  
	public int flags = 0;  
	public short fileOffset = 0;  
	public short fileExtension = 0;  
	public String defExt = null;  
	public IntPtr custData = IntPtr.Zero;  
	public IntPtr hook = IntPtr.Zero;  
	public String templateName = null;  
	public IntPtr reservedPtr = IntPtr.Zero;  
	public int reservedInt = 0;  
	public int flagsEx = 0;  
}  

public class WindowDll  
{  
	[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]  
	public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);  
	public static bool GetOpenFileName1([In, Out] OpenFileName ofn)  
	{  
		return GetOpenFileName(ofn);  
	}  
}  

UploadImage.cs如下:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class Upload : MonoBehaviour {
	public Texture2D img = null;
	private bool click = false;
	void OpenDialog()
	{
		click = true;
	}
	void EnterImage()
	{
		OpenFileName ofn = new OpenFileName();
		ofn.structSize = Marshal.SizeOf(ofn);  
		
		ofn.filter = "All Files\0*.*\0\0";  
		
		ofn.file = new string(new char[256]);  
		
		ofn.maxFile = ofn.file.Length;  
		
		ofn.fileTitle = new string(new char[64]);  
		
		ofn.maxFileTitle = ofn.fileTitle.Length;  
		
		ofn.initialDir = UnityEngine.Application.dataPath;//默认路径  
		
		ofn.title = "Open Project";  
		
		ofn.defExt = "JPG";//显示文件的类型  
		//注意 一下项目不一定要全选 但是0x00000008项不要缺少  
		ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR  

		if(WindowDll.GetOpenFileName(ofn))
		{
			StartCoroutine(GetTexture(ofn.file));
		}

	}

	IEnumerator GetTexture(string url)
	{
		WWW wwwTexture = new WWW ("file://" + url);
		yield return wwwTexture;
		if(wwwTexture.isDone)
			img = wwwTexture.texture;
	}

	void OnGUI()
	{
		if(click)
		{
			EnterImage();
			click = false;
		}
		if (img != null)
			GUI.DrawTexture (new Rect(Screen.width/2 - img.width/2,Screen.height/2 - img.height,img.width,img.height),img);
	}
	
}


2015-11-27 15:55:48 u014725878 阅读数 3243

1.找到System.Windows.Forms.dll,并放在project中的Plugins文件夹下。 “D:\Unity3D\Editor\Data\Mono\lib\mono\2.0\System.Windows.Forms.dll”

2.打开Player Settings 把.NET 2.0 Subset 改为.NET 2.0;

<span style="font-size:14px;">using UnityEngine;
using System.Collections;
using System.Windows.Forms;
public class screenshots : MonoBehaviour {
	// Use this for initialization
	void Start () {
	}
	// Update is called once per frame
	void Update () {
	
	}
	public void Screen(){
		SaveFileDialog saveLog = new SaveFileDialog ();
		saveLog.InitialDirectory="c:\\";
		saveLog.Filter="Image File(*.JPG;*.BMP;*.PNG)|*.JPG;*.BMP;*.PNG|All files(*.*)|*.*";
		DialogResult result = saveLog.ShowDialog ();
		if (result == DialogResult.OK) {
			string path=saveLog.FileName;
			UnityEngine.Application.CaptureScreenshot(path);
		}
	}
}</span><strong style="color: rgb(102, 51, 0);font-size:18px;">
</strong>
为按钮绑定一个Screen()的方法

在编辑器运行,当出现此弹窗,确定忽略即可。发布成桌面客户端是不会有这个弹窗的。


下面来看运行效果


2015-05-06 17:42:42 menghuangxiao 阅读数 4784

不久之前买了小米平板,就想着用Unity3d做个小游戏放在平板上玩玩,匆匆做了个资源加载界面就发布apk到平板上,结果提示资源加载失败,找不到资源文件。在网上找了半天资料都没解决问题,最后发现自己犯了个最愚蠢的问题,就是StreamingAssets文件夹名称有问题,我写成了StreamingAsset,真是被自己给坑到了。


下面总结下Unity3d发布Android版通过WWW加载本地AssetBundle资源的注意事项:

(1)一定要将需要加载的AssetBundle资源文件放在StreamingAssets目录下,因为Android只能加载StreamingAssets中的内容。

(2)打包AssetBundle资源包时需要打包平台为BuildTarget.Android

using UnityEngine;
using System.Collections;
using UnityEditor;//必须引用此类
public class ExportAssetBundles : MonoBehaviour
{
    /// <summary>
    /// 将所选择的的物体和物体有依赖关系的对象一起打包
    /// </summary>
    [MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
    static void ExportResource()
    {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0)
        {
            // Build the resource file from the active selection.
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies |
BuildAssetBundleOptions.CompleteAssets, BuildTarget.Android);
            Selection.objects = selection;
        }
    }
    /// <summary>
    /// 只打包选择的物体
    /// </summary>
    [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
    static void ExportResourceNoTrack()
    {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0)
        {
            // Build the resource file from the active selection.
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
        }
    }
}
(3)注意加载文件的路径,判断运行平台请用Application.platform == RuntimePlatform.Android这种方式。

Windows :  path = = Application.dataPath + "/StreamingAssets";

On iOS: path = Application.dataPath + "/Raw";

Android:path = "jar:file://" + Application.dataPath + "!/assets/";

Application.platform == RuntimePlatform.Android

下面是我的代码:

using System;
using System.Collections;
using UnityEngine;

namespace HKScripts
{
    class HKLoadResource : MonoBehaviour
    {
        public static float progress = 0;

        private WWW www = null;
        void Awake()
        {
            StartCoroutine("loadEnvironment");
        }

        void Update()
        {
            if (www!=null)
            {
                progress = www.progress;
            }
        }

        IEnumerator loadEnvironment()
        {
            string url = "";
            if (Application.platform == RuntimePlatform.Android)
                url = "jar:file://" + Application.dataPath + "!/assets/Environment.unity3d";
            else 
                url = "file:///" + Application.dataPath + "/../Environment.unity3d";
            Debug.LogError(url);
            www = new WWW(url);
            yield return www;
            if (www.error != null)
            {
                GameObject.FindGameObjectWithTag("TipLabel").GetComponent<UILabel>().text = "路径:" + url + "错误:" + www.error;
                Debug.LogError(www.error);
                yield return null;
            }

        }
    
    }
}



2014-04-23 17:35:32 liulala16 阅读数 16265

            创建一个MyFile.txt文件、将它放到streamingAssetsPath文件夹下(没有的话手动创建一个)

             var fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, "MyFile.txt");

FileInfo fInfo0 = new FileInfo(fileAddress);
string s = "";
if (fInfo0.Exists)
{
StreamReader r = new StreamReader(fileAddress);
s = r.ReadToEnd();
    debug.log(s);

    }

             打印出来的就是txt文件的内容

没有更多推荐了,返回首页