You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中C#代码Android移动端失效问题排查与解决方案咨询

Fixing Your Unity C# Code for Android Compatibility

Hey there! Let me start by reassuring you: C# works perfectly on Android in Unity—Unity compiles your C# code to intermediate language (IL) and then converts it to Android's native bytecode (either via Mono or IL2CPP). The problem here isn't that C# can't run on mobile, but rather a few platform-specific issues in your code. Let's walk through the fixes step by step.

Key Issues in Your Code

1. Invalid File Path for Writing on Android

On Android, Application.dataPath points to the read-only APK assets directory—you can't write files here. Instead, you need to use Application.persistentDataPath, which is a dedicated, writable directory for your app on the device's storage.

2. Potential Texture Format Compatibility

The TextureFormat.RGB24 and TextureFormat.ARGB32 you're using might not be supported on all Android GPUs. Switching to more universally supported formats like TextureFormat.RGBA32 or letting Unity auto-select the best format can prevent rendering issues.

3. Minor: IMGUI vs. UGUI Interaction

While not the main culprit, mixing the old OnGUI() system (IMGUI) with UGUI buttons can sometimes lead to input or rendering quirks on mobile. We'll keep the functionality but note this for future reference.

Modified Working Code

Here's your code with the critical fixes applied:

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;

    void Start () {
        // Use RGBA32 for better cross-platform compatibility
        screenCap = new Texture2D(300, 200, TextureFormat.RGBA32, false);
        border = new Texture2D(2, 2, TextureFormat.RGBA32, false);
        border.Apply();
        m_YourFirstButton.onClick.AddListener(TaskOnClick);
    }

    void Update () { }

    public void TaskOnClick() {
        StartCoroutine(Capture()); // Avoid string-based coroutine calls for better performance
    }

    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();
        
        // Capture the desired area
        screenCap.ReadPixels(new Rect(198, 98, 298, 198), 0, 0);
        screenCap.Apply();
        
        byte[] bytes = screenCap.EncodeToPNG();
        
        // Use persistentDataPath instead of dataPath for Android writable storage
        string savePath = Path.Combine(Application.persistentDataPath, "SavedScreen.png");
        File.WriteAllBytes(savePath, bytes);
        
        // Optional: Log the path so you can find the file on the device
        Debug.Log("Screenshot saved to: " + savePath);
        
        shot = true;
    }
}

Additional Steps to Debug

  • Check Android Logcat: In Unity, go to Window > General > Console, then click the dropdown in the top-right and select Android Logcat. This will show you any runtime errors (like file access denied) that are happening on the device.
  • Request Storage Permissions: On newer Android versions (API 23+), you need to request WRITE_EXTERNAL_STORAGE permission if you want to save files to public storage. If you're using persistentDataPath, you might not need this, but it's good to add permission checks if you plan to share the file later.
  • Test with IL2CPP: If you're using Mono as the scripting backend, try switching to IL2CPP in Player Settings > Other Settings > Scripting Backend—it often fixes platform-specific compatibility issues and improves performance.

Final Notes

Unity handles most cross-platform adaptation automatically, but you do need to watch out for platform-specific APIs (like file paths) and hardware compatibility (like texture formats). With these fixes, your code should run smoothly on Android just like it does on desktop.

内容的提问来源于stack exchange,提问作者Bilge Yücel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:28:17