docs.unity3d.com
    Show / Hide Table of Contents

    Run Python instructions from C#

    Use the PythonRunner.RunString method to execute a single Python instruction from C#.

    Example: create a menu item that executes a simple Python instruction

    C# code

    The following C# code creates a menu item that logs "Hello World!" in the Unity Console:

    using UnityEditor.Scripting.Python;
    using UnityEditor;
    
    public class HelloWorld
    {
        [MenuItem("MyPythonScripts/Log Hello World")]
        static void PrintHelloWorldFromPython()
        {
            PythonRunner.RunString(@"
                    import UnityEngine;
                    UnityEngine.Debug.Log('Hello World!')
                    ");
        }
    }
    

    Test

    From the main menu of the Editor, select MyPythonScripts > Log Hello World.

    The text Hello World! should appear in the Unity Console.

    Additional references

    • Call Python script files from C#
    • Call Python APIs from C#
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023