繁体   English   中英

如何在Unity中使用C#代码在移动设备上工作?

[英]How can I use C# code in Unity to work on mobile?

我编写了一段C#代码以在Unity中的移动设备中工作。 我在网络摄像头上进行了测试,效果很好。

但是,当我将其构建为APK时,它无法在我的移动设备上运行,问题显然出在C#代码上。 我不熟悉移动环境,因此不确定C#代码是否可以由Android设备运行,但是我认为Unity可以解决这个问题。

我是否应该基本接受C#不能在移动设备上运行或有解决方案?

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;


public class MenuScript : MonoBehaviour {

    Texture2D screenCap;
    Texture2D border;
    bool shot = false;
    public Button m_YourFirstButton;

    // Use this for initialization
    void Start () {

        screenCap = new Texture2D(300, 200, TextureFormat.RGB24, false); // 1
        border = new Texture2D(2, 2, TextureFormat.ARGB32, false); // 2
        border.Apply();
        m_YourFirstButton.onClick.AddListener(TaskOnClick);
    }

    // Update is called once per frame
    void Update () {
    }

    public void TaskOnClick()
    {
        StartCoroutine("Capture");
    }

    void OnGUI()
    {
        GUI.DrawTexture(new Rect(200, 100, 300, 2), border, ScaleMode.StretchToFill); // Top
        GUI.DrawTexture(new Rect(200, 300, 300, 2), border, ScaleMode.StretchToFill); // Bottom
        GUI.DrawTexture(new Rect(200, 100, 2, 200), border, ScaleMode.StretchToFill); // Left
        GUI.DrawTexture(new Rect(500, 100, 2, 200), border, ScaleMode.StretchToFill); // Right

        if (shot)
        {
            GUI.DrawTexture(new Rect(10, 10, 60, 40), screenCap, ScaleMode.StretchToFill);
        }
    }

    IEnumerator Capture()
    {
        yield return new WaitForEndOfFrame();
        screenCap.ReadPixels(new Rect(198, 98, 298, 198), 0, 0);
        screenCap.Apply();
        byte[] bytes = screenCap.EncodeToPNG();
        //Object.Destroy(screenCap);

        // For testing purposes, also write to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/SavedScreen.png", bytes);
        shot = true;
    }

}

我假设您已经在Unity中编写了此代码,并且可以在编辑器中使用。 您对问题的陈述有些奇怪,因此我不得不承担这些责任。

之所以无法在移动设备上运行,很可能是因为您正在使用Application.dataPath 这不应该用于Android。 最明显的原因是Android权限,它可能不允许您写入SD卡或内部存储。 您也很可能有UnauthorizedAccessException

要检查Android上的版本出了什么问题,应使用logcat。 当您的设备通过电缆连接到PC时,打开命令提示符访问包含adb.exe的文件夹,然后使用以下命令: adb.exe logcat -s Unity

然后在移动设备上启动APK。 这将向您显示所有Debug.Log执行和所有异常。 然后,您可以调试代码。

有关日志文件的更多信息,请参见此处。

祝好运!

Unity使用的.NET库是.NET的旧子集。 详细信息: 当Mono支持.NET 3.5时,为什么Unity使用.NET 2.0?

您可以更改Unity使用的.NET版本,但是它将无法在移动设备上运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM