1、建立一个空的安卓工程
2、在unity安装目录下找到classes.jar文件并导入到工程中的libs文件夹下(classes.jar目录为:unity安装目录\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Development\Classes)
3、右键工程中的classes.jar-->BuildPath-->Add to Build Path
4、修改MainActivity.java的代码
package com.player.fish;(这里是自己的包名)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends UnityPlayerActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PHOTO_REQUEST_CODE = 1;//相册
public static final int PHOTOHRAPH = 2;// 拍照
public static final int PHOTOZOOM=3;//裁剪
private static final boolean DEBUG = true;
private String savePath=""; //图片保存路径
private String picturePath=""; //最终上传的文件路径
private String unitygameobjectName = "BGPlane"; //Unity 中对应挂脚本对象的名称
public static final int NONE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
//调用相机
public void Takephoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
startActivityForResult(intent, PHOTOHRAPH);
}
//调用相册
public void OpenGallery()
{
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, PHOTO_REQUEST_CODE);
}
//裁剪图片
public void CropPhoto(Uri uri) {
//调用裁剪器
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 开启裁剪功能
intent.putExtra("crop", "true");
//设置宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
//裁剪图片宽高
intent.putExtra("outputX", 100);
intent.putExtra("outputY", 100);
//请求返回数据
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTOZOOM);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == NONE){
return;
}
//相册
else if(PHOTO_REQUEST_CODE == requestCode){
if(data == null){
return;
}
Uri uri = data.getData();
savePath = getImagePath(uri);
if(DEBUG){
Log.d(TAG, savePath);
}
CropPhoto(uri);
}
//相机
else if (requestCode == PHOTOHRAPH) {
savePath = Environment.getExternalStorageDirectory() + "/temp.jpg";
if(DEBUG){
Log.e("path:", savePath);
}
CropPhoto(Uri.fromFile(new File(savePath)));
try {
Bitmap bitmap = BitmapFactory.decodeFile(savePath);
SaveBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
//裁剪
else if(PHOTOZOOM == requestCode){
Bundle extras = data.getExtras();
if(extras!=null)
{
try{
Bitmap photo=extras.getParcelable("data");
SaveBitmap(photo);
}catch(IOException e)
{
e.printStackTrace();
}
}
UnityPlayer.UnitySendMessage(unitygameobjectName, "GetImagePath", picturePath);
}
}
private String getImagePath(Uri uri)
{
if(null == uri) return null;
String path = null;
final String scheme = uri.getScheme();
if (null == scheme) {
path = uri.getPath();
} else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
path = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, proj, null, null,
null);
int nPhotoColumn = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (null != cursor) {
cursor.moveToFirst();
path = cursor.getString(nPhotoColumn);
}
cursor.close();
}
return path;
}
public void SaveBitmap(Bitmap bitmap) throws IOException {
FileOutputStream fOut = null;
String path = "/mnt/sdcard/DCIM/";
try {
//查看这个路径是否存在,
//如果并没有这个路径,
//创建这个路径
File destDir = new File(path);
if (!destDir.exists())
{
destDir.mkdirs();
}
String FILE_NAME = System.currentTimeMillis() + ".jpg";
picturePath=path + "/" + FILE_NAME;
fOut = new FileOutputStream(path + "/" + FILE_NAME) ;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//将Bitmap对象写入本地路径中
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5、修改AndrlidManifest.xml,设置权限及相关信息
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.player.fish"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name="com.player.fish.MainActivity"
android:screenOrientation="landscape"(锁定横屏,竖屏的可以把这行删掉(注意横竖屏不匹配会导致闪退))
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>
6、点击Project-->把Build Automatically前面的勾去掉,-->点击Clean-->Clean All Project-->OK
7、点击Project-->BuildProject
8、Win+R调出运行窗口-->CMD
9、将控制台地址改为安卓工程中classes文件夹地址(安卓工程目录\bin\classes)
更改方式为:目标磁盘+“:”-->回车变更磁盘地址
Cd\+磁盘后面的地址-->回车变更后面的文件夹地址
比如我的classes文件夹地址为D:\AndroidSDK\FishTest\bin\classes
10、将地址改为classes文件夹下后,将classes文件夹下面的所有jar包打包在一起,具体命令为 jar -vcf 压缩包名.jar *
比如我将jar包压缩为class.jar,那么命令为 jar -vcf class.jar *,打出来的包就在classes文件夹俩面
11、打开刚刚打出来的jar包(不是解压缩),按照包名的路径打开文件夹(我的包名为com.player.fish,所以文件夹结构为com-->player-->fish),删除里面所有带R和$的文件,否则打包回报错
12、在Unity工程中建立Plugins-->Android文件夹,将安卓工程中的AndroidManifest.xml文件以及assets文件夹还有res文件夹导入到Android文件夹下面,在Android文件夹下新建bin文件夹,将刚刚打出来的jar包放进去
13、准备工作全部完成,接下来开始写C#脚本
private void Awake()
{
//将挂载此脚本的物体的名字改为和java脚本中的名字一致
this.gameObject.name = "BGPlane";
}
//打开相册
public void OpenPhoto()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic
( "currentActivity");jo.Call("OpenGallery");
}
//打开相机
public void OpenCamera()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic
( "currentActivity");jo.Call("Takephoto");
}
//获取图片的调用
public void GetImagePath(string imagePath)
{
if (imagePath == null)
return;
StartCoroutine("LoadImage", imagePath);
}
private IEnumerator LoadImage(string imagePath)
{
WWW www = new WWW("file://" + imagePath);
yield return www;
if (www.error == null)
{
//成功读取图片,写自己的逻辑
this.GetComponent
().material.mainTexture = www.texture; }
else
{
Debug.LogError("WWW Error:" + www.error);
}
}
14、全部完成,打包(注意:playersetting中的包名要和安卓工程以及xml文件中的包名一致,挂在C#脚本的物体的名字在MainActivity.java中已经定义好,要保持一致;C#脚本中所有的方法都是通过消息传递来通知的,方法名要和MainActivity.java中定义的保持一致)