Skip to content

C# jagged arrays and lists make Unity crash the second time #1713

@Zulex

Description

@Zulex

Environment

  • Pythonnet version: 3.0.0-preview2022-03-03
  • Python version: 3.8.9
  • Operating System: Windows 10
  • .NET Runtime: 4
  • Unity 2020.3.12f1

Details

  • Describe what you were trying to get done.

Trying to send a jagged array or List of float 1D array to Python via C# in Unity. This works the first time I press play in Unity but crashes on the second time without any errors.

  • See below for a C# script that creates a normal 2D array, a jagged array and a listarray. If I send the normal array, it works fine restarting. However the jagged array and list do make unity crash if I press play for a second time.
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Python.Runtime;

public class MinimalExample : MonoBehaviour
{
    float[,] twoDimArray = null;
    float[][] jaggedArray = null;
    List<float[]> listArray = new List<float[]>();

    void Start()
    {
        //Adjust the line below to your target python version in the correct folder
        Runtime.PythonDLL = Application.dataPath + "/StreamingAssets/embeddedPy/python38.dll";

        for (int i = 0; i<2; i++)
        {
            float[] temp = { 1.2345679f, 9.87654321f, 1.23456789f};
            listArray.Add(temp);
        }

        twoDimArray = new float[,] { { 1.2345679f, 9.87654321f, 1.23456789f }, { 1.2345679f, 9.87654321f, 1.23456789f } };

        jaggedArray = listArray.ToArray();
        SendToPython(twoDimArray, jaggedArray, listArray);
    }

    void SendToPython(float[,] ex2, float[][] ex3, List<float[]> ex4)
    {

        using (Py.GIL())
        {
            dynamic py_sys = Py.Import("sys");
            string site_pkg = "Lib\\site-packages";
            py_sys.path.insert(0, Path.Combine(Application.streamingAssetsPath, site_pkg));
            dynamic pythonScript = Py.Import("MinimalExample");

            //If we use ex2 here as input, restarting inside unity works. Restarting does not work for ex3 and ex4
            dynamic returnedValue = pythonScript.ReturnValue(ex2); 

            Debug.Log(returnedValue);
        }
    }
}
import numpy as np

def ReturnValue(data):
    result = np.asarray(data)
    return result
  • A simple solution is to transform my jagged arrays and lists to normal arrays. However I was wondering if I am doing something wrong or this is indeed an unknown bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions