Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Python interpreter in Unity

Discussion in 'Scripting' started by noamgat, Apr 20, 2011.

  1. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    After working a bit with maya/blender, I noticed that the interpreter is very useful for programatically editing the scene.
    Yes, unity gives us lots of flexibility for scripting, but its a bit overkill in some cases (for example, batch-placing objects in the scene at edit time).

    I thought that unity could use an interpreter, so I made one!

    To use, just import the attached unity package and go to Window->Python Interpreter.
    If you want to see an example, have a look at the screenshot where I create a cube and change a few properties.

    A few notes :
    1 - This is pure python (I used IronPython), and not unity's variant of python. However, you can access all of the unity classes with the same name conventions as the C# API.
    2 - History colors : Green = commands, Blue = return values, Black = Python output, Red = Errors.
    3 - The editor is really basic. I just did the simplest thing that is functional.

    As for the future, the main problem is of course the editor. I would like to have
    a - Autocompletion
    b - command history via up/down arrows
    c - ability to copy/paste text from the history view
    d - ability to load/save scripts, and perhaps open additional tabs.

    I feel that the EditorWindow API is lacking in its flexibility, for example the Input.XXX set of functions isnt available. How would I solve b?

    Anyway, I will release it soon to the Asset Store (for free), and will be really happy if I'll be able to add some of the features to the editor.

    If anyone wants to contribute, either by improving the editor or by giving me tips on how to do it within a Unity EditorWindow, I'll be very happy (code contributions will be credited, of course!).

    As always, I'm open to comments, suggestions and bug reports for this script.
    Have fun!
     

    Attached Files:

    Last edited: May 15, 2011
  2. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    wow, this looks pretty awesome!! the fact that you can access the unity API with it is really really cool!

    Now, what would really make it shine would be to be able to interpret code at runtime... That would be a complete modding interface in a box!

    Really good work there! thanks for making it available for everyone!!

    Cheers
     
  3. tODDk

    tODDk

    Joined:
    Aug 14, 2009
    Posts:
    50
    I'm going to check this out. Many thanks!
     
  4. liverolA

    liverolA

    Joined:
    Feb 10, 2009
    Posts:
    347
    better if we can use this as game script interpreter!!
    Keep up the good work
     
  5. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    I'm not sure I understand you. You can already open the interpreter whenever you want (including in-game from the editor) and type code which will be evaluated instantly.
     
  6. Vinícius Sanctus

    Vinícius Sanctus

    Joined:
    Dec 14, 2009
    Posts:
    282
    Pretty awesome friend! Altought i suck at python so far =)
     
  7. cemC

    cemC

    Joined:
    Dec 23, 2010
    Posts:
    214
    quite interesting work. Can we use the blender or maya functions inside the unity. ? or Can we use the Blender scripts inside the unity3D?
     
  8. liverolA

    liverolA

    Joined:
    Feb 10, 2009
    Posts:
    347
    more examples please!
     
  9. Tinus

    Tinus

    Joined:
    Apr 6, 2009
    Posts:
    437
    Wow, I had no idea it was that easy to set up. Iron Python go! Thanks for sharing it. :)

    It also seems easy to build an in-game GUI around this, which would make for a stupendously powerful console window. Runtime modding, administrative tasks, game master stuff. Major coolness.
     
  10. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    What I mean is, being able to interpret .py files loaded at runtime, from the standalone build, so as to enable scripting access to modders.

    I assumed, from the OP, that the interpreter only did it's thing while in editor mode (or running the unbuilt game from the game window)... but if it's possible to load scripts and run them at runtime (i.e. the built client), then the modding potential is virtually limitless. :D

    Currently there is a Lua interface on the Asset Store, that enables one to load a .lua script and interpret it at runtime... the downside is that the Lua scripts don't have implicit access to the Unity API, so you have to expose methods to get and set pretty much anything that will talk to the Unity API in one way or another...

    This here has the advantage that you can simply use the API from the script, so you can do just about anything in your script, regardless of whether your game exposes that function or not. (that can be a good thing and a bad thing I guess... depends on the kind of game you're making)

    Cheers
     
  11. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    Thanks for the feedback! I'll probably refactor the work so that you'll be able to run code from inside the game as well (its the same thing, just need to move things around a bit).

    As for having a real editor, I decided to tap into an existing one instead of writing one on my own. I attached a WIP pic :

    You can write code in MonoDevelop, and then click in the menu and it will send it to the python interpreter and execute it there. No autocompletion yet, but its an editor.

    I'll probably release it soon, and then samples will be easy to copy/paste/move around.
     

    Attached Files:

    Enviy likes this.
  12. cemC

    cemC

    Joined:
    Dec 23, 2010
    Posts:
    214
    More specifically, i want to use Blender scripts or functions inside the Unity3D. For example Blender Script(Curve) is used for create curve. Is that possible to use this inside the Unity3D by using this tool.?
     
  13. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    This would make this the single most useful unity extension ever!!
    Can't wait for a release!!

    About editors, would it be at all possible to hook up the Unity API with Eclipse+PyDev? That has to be the best Python IDE out there, and it has all the autocompletion and nice features you'd expect from an IDE... if only we could get class info from Unity's API in there, it'd be perfect! Something like the way Visual Studio can grab code info... I'm sure Unity has it's Boo libraries exposed there somewhere... PyDev can get into that and provide all the autocompletion (well, at least as much as is possible with Python ;) ).


    Oh, and one more question:

    Is it possible to call python functions from standard C# or JS scripts?
    If it were possible to load in a .py file, and by script call various functions already defined there... imagine the modding possibilities...

    Cheers
     
    Last edited: Apr 25, 2011
  14. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    @cemC : You have to distinguish between programming language (C#,Python,Javascript etc) and environment API (Unity/Blender/Maya etc). While the language is the same, those blender functions use blender API calls which are not available when python code is ran from unity. So you can not run those scripts as is. However, if you would re-implement all the library functions they use you could use them.

    @HarvesteR

    1 ) I moved the python execution to another class, but for some reason I'm getting an error when I put that class outside of the Editor folder. I might raise that question to the unity guys. I'll post the updated version here soon and people will be able to tackle it as well.

    2 ) I integrated MonoDevelop with the environment, since it is the editor that comes when you install unity. I don't want people who want to use this extension to have to install Eclipse. However, since everything is open source, anyone can extend PyDev to support this as well (the protocols are trivial)

    3 ) Once problem 1 is solved, you'll be able to create the python environment in a game object, and access its RunCode function from scripts. That will allow you to run python code from wherever you want (load .py file into string -> send it to RunCode -> done!)
     
  15. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    Oh man, this is looking real good!

    If I get some free time this week (here's hoping), I'll try to help out with those compilation problems.

    Again, a million thanks for this! It's shaping up to be a complete solution for my own project here. I'll definitely help out in polishing it once we get to the Modding API stage of development (which should be next week) :)

    Cheers
     
  16. r618

    r618

    Joined:
    Jan 19, 2009
    Posts:
    1,303
    Hi Noman, i just found python interpreter on the asset store; any luck with the runtime capabilities so far ?
     
  17. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    I got it working eventually. I just submitted an update to the asset store that gets it working. Stay tuned :)

    Also note that since I put in more effort than I expected into this project (and ended up solving all of the issues on my own), this plugin will not remain free forever. I will be keeping it free until the end of the month (May 2011) for the sake of those who participated in the discussion here, but it will get a price tag (probably not a high one) afterwards.
     
  18. r618

    r618

    Joined:
    Jan 19, 2009
    Posts:
    1,303
    Thanks for the update, great news!
     
  19. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
  20. Dreality

    Dreality

    Joined:
    Aug 9, 2012
    Posts:
    1
    Did you include the path where your class is located in the PYTHONPATH lib?
     
  21. vickyboy47

    vickyboy47

    Joined:
    Oct 24, 2013
    Posts:
    1
    Hi Noman,

    This is Vicky from Singapore. I am a Computer Vision researcher currently working in hand tracking and multi-object tracking.

    I have a query with regard to the "Python interpreter for Unity". I saw it in the Asset store. Kudos to you for creating the interpreter :). Sounded really great…. :) :)

    As of now, we are building a Virtual Reality demo for our Object tracking framework, which was coded fully in Python. The output of our Object tracking framework would be represented in 3D Virtual space. We have decided to build this Virtual Reality demo using Unity 3D. Now my doubt is… Can I install third party libraries on top of the "Python interpreter for Unity" ?? If yes, I would go forward and purchase it. Our tracking framework makes use of libraries like OpenCV, numPy, sciPy, scikit-learn, scikit-image, and a few more. As per my understanding, in order to execute (or integrate) our framework from the Python interpreter for Unity, we need to have all these libraries compiled for your interpreter too. (Correct me if I am wrong??).

    Or is there any other way to establish a connection between our tracking framework coded in Python and the 3D environment created in Unity ?

    It would be great if you can help me with this.

    Thanks a ton

    Vicky
     
  22. noamgat

    noamgat

    Joined:
    Nov 22, 2009
    Posts:
    125
    This plugin uses IronPython 2.6.1 internally (the last version to support .Net 2.0) and not a native python implementation. So the way I see it, you have two choices :
    1 - Find versions of all the libraries you need that have been ported to work with this version of IronPython
    2 - Use a remote invocation library to connect between this instance of python and a native instance of python that can use these libraries (something like rPyC perhaps). I have never done this myself so I don't know if it is possible.

    Good luck!
     
  23. gressettd

    gressettd

    Joined:
    Nov 6, 2012
    Posts:
    3
    Working in Unity 4.3, finding this asset to be very unstable, crashing unity every time I try to use it.

    For example, with this code:


    var code = pythonCode;
    _minShoppersFn = (int curr, DateTime dt) =>
    {
    _env.ExposeVariable("current", curr);
    _env.ExposeVariable("time", dt);

    var res = _env.RunCommand(code);

    if(null != res.exception)
    throw res.exception;

    var ret = int.Parse(res.output.Trim ());
    return ret;
    };

    var test = _minShoppersFn(100, DateTime.Now);
    Debug.Log (test);

    with this script:

    import clr
    import System
    from System import DateTime, DayOfWeek

    if time.DayOfWeek == DayOfWeek.Friday and time.Hour < 21 and time.Hour > 15:
    print 220
    elif time.Hour > 9 and time.Hour < 12:
    print 100
    elif time.Hour >= 12 and time.hour < 16:
    print 50
    elif time.Hour >= 16 and time.hour < 20:
    print 120
    elif time.Hour >= 20 and time.hour < 22:
    print 80
    else:
    print 0


    It runs all the way through, then unity crashes, every time. I've tried creating a function in the script and then getting that out of the script scope as a variable, but it still crashes after you execute the script.

    Is there some kind of thread safety issue I'm unaware of here?
     
  24. shady_2242

    shady_2242

    Joined:
    Jan 11, 2014
    Posts:
    1
    where's the download file?
     
    enc216 likes this.
  25. LlanaeroXy

    LlanaeroXy

    Joined:
    Feb 4, 2016
    Posts:
    1
    hi
    sorry, where is the attached unity package?
     
  26. Root13

    Root13

    Joined:
    Nov 2, 2016
    Posts:
    12
  27. lorenzoidd

    lorenzoidd

    Joined:
    Apr 27, 2018
    Posts:
    3
    does this let us use python instead of C# or JavaScript to code?
     
  28. SandiagoChan

    SandiagoChan

    Joined:
    Aug 8, 2017
    Posts:
    19
    It outputs err when using import expression,here is my python code:
    Code (CSharp):
    1. import sys
    2. import os
    3.  
    4. print('success')
    It runs successfully on cmd window,but outputs exception:"Python exception : No module named os".
    By the way,my unity version:2017.4.5f1, and package is "Python Interpreter_1.6.unitypackage".
     
  29. santiagolopezpereyra

    santiagolopezpereyra

    Joined:
    Feb 21, 2018
    Posts:
    91
    Is this still being developed? How can we contribute; is this open source?
     
  30. Papparoo

    Papparoo

    Joined:
    Mar 30, 2013
    Posts:
    2
    Is this still available?
     
  31. SweatyChair

    SweatyChair

    Joined:
    Feb 15, 2016
    Posts:
    140
    I know this is a very old thread, recently I'm looking for runtime Python interpreter (player can code python) like Lua... Is there anything like that?
     
  32. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,276
    SweatyChair likes this.
  33. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    This would be super usefull if you allow us to save scripts and assign them to menus so I can share my scripts with other devs in our team.
     
  34. SweatyChair

    SweatyChair

    Joined:
    Feb 15, 2016
    Posts:
    140
    Thx josh, I actually went there from Google search too but havn't went too deep, will take a look soon.
     
    joshcamas likes this.
  35. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,276
    It's really cool stuff! I've ended up using it for my dialog / quest systems :))
     
  36. skyser5

    skyser5

    Joined:
    Jun 11, 2015
    Posts:
    24
    Does anyone know if this is possible: I would like to have a Python script that calls out to a C# method and blocks (does not continue to the next bit of Python script) until the C# method finishes.
     
  37. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,276
    Is that not how it works by default? Pretty sure its all on one thread
     
    Joe-Censored likes this.
  38. skyser5

    skyser5

    Joined:
    Jun 11, 2015
    Posts:
    24
    Right. I should have been more specific. I want to be able to do stuff like have Python call a C# function that starts a coroutine or a tween. I want Python to block somehow until the coroutine or tween have finished.
     
  39. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,276
    Ahh I see. Well, you can't block the python code, that would block the thread. Just like blocking c# code would do the same. However, I believe you could simply use events, just like how you would for C#.
     
  40. skyser5

    skyser5

    Joined:
    Jun 11, 2015
    Posts:
    24
    Thanks for the tip. I'm not familiar with Python events, but I'll investigate.
     
  41. skyser5

    skyser5

    Joined:
    Jun 11, 2015
    Posts:
    24
    I found out Python supports coroutines. I'm investigating that first.
     
    GilbertoBitt likes this.