系统环境:win10 + Unity 2018.3.13f1 (64-bit)
1. 安装NDK
解压下载后的文件夹,将文件夹路径添加到系统环境变量Path中
2. 编写文件
makeSo文件夹名称可以修改,但jni不要修改
参考链接:https://docs.unity3d.com/Manual/PluginInspector.html
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := NativeCode
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES := NaviteCode.cpp
LOCAL_LDLIBS := -llog -landroid
LOCAL_CFLAGS := -DANDROID_NDK
include $(BUILD_SHARED_LIBRARY)
APP_STL := c++_static
APP_CPPFLAGS := -frtti -std=c++11
APP_PLATFORM := android-19
APP_CFLAGS += -Wno-error=format-security
APP_BUILD_SCRIPT := Android.mk
APP_ABI := armeabi-v7a x86
NaviteCode.cpp
#include "NaviteCode.h"
extern "C" {
int MyAddFunc(int _a, int _b)
{
return _a + _b;
}
}
NaviteCode.h
#ifndef __NativeCode_H__
#define __NativeCode_H__
extern "C"
{
int MyAddFunc(int _a, int _b);
}
#endif
3. ndk-build
Win+r:输入cmd
会生成obj libs两个文件夹
4. 新建unity工程
将libs文件夹复制到Assets/Plugins/Android,没有则自己创建
show.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class show : MonoBehaviour
{
[DllImport("NativeCode")]
public static extern int MyAddFunc(int x, int y);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
gameObject.transform.Translate(new Vector3(0, 0, MyAddFunc(1, 1)));
}
}
将show.cs绑定到一个物体中,实现运动功能
5.生成apk
file->Build Settings
6.注意事项
不论怎么选择,editor中是无法运行程序的,会一直报错dllnotfoundexception,发布成apk在安卓真机或模拟器上运行即可