ref:
Instruction
import pip pip.main(["install","PySide2"])
import UnityEngine as unity obj_list = unity.Object.FindObjectsOfType(unity.GameObject) for each_obj in obj_list: print(each_obj.name)
Once above basic setup for python is done for unity, I would like to get Qt working and interaction with unity.
(Note, don't launch python Qt code from Python Console inside Unity, it will show Qt window, but it also block Unity UI interaction, run it from c sharp script)
After a bit research, mainly from video of Indie-Pixel's Python for Unity 3D 2020!!: (https://www.youtube.com/watch?v=3UOlN8FcNbE)
I got it further into make the PySide2 UI interaction working. the main thing is print(). you need to
import UnityEngine as unity unity.Debug.Log("use this way of print in unity when run from python script")
Steps:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PyTool : MonoBehaviour { }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.Scripting.Python; [CustomEditor(typeof(PyTool))] public class PyToolEditor : Editor { PyTool targetTool; private void OnEnable() { targetTool = (PyTool)target; } public override void OnInspectorGUI() { if (GUILayout.Button("PyTool", GUILayout.Height(35))) { Debug.Log("Hello PyTool"); string cur_path = Application.dataPath; Debug.Log(cur_path); string py_file = cur_path + "/PythonScript/UnityPythonRun.py"; Debug.Log(py_file); PythonRunner.RunFile(py_file); } if (GUILayout.Button("TestQ", GUILayout.Height(35))) { Debug.Log("Hello TestQ"); string cur_path = Application.dataPath; string py_file = cur_path + "/PythonScript/TestQ.py"; Debug.Log(py_file); PythonRunner.RunFile(py_file); } } }
import UnityEngine as unity def u_print(info): unity.Debug.Log(info) obj_list = unity.Object.FindObjectsOfType(unity.GameObject) for each_obj in obj_list: print(each_obj.name) u_print(each_obj.name) print('python here') u_print('python here')
import UnityEngine as unity from PySide2 import QtWidgets class TestUI(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) # win self.setWindowTitle("TestQ") # ui part main_widget = QtWidgets.QWidget() self.setCentralWidget(main_widget) main_layout = QtWidgets.QVBoxLayout() main_widget.setLayout(main_layout) test_btn = QtWidgets.QPushButton("List Object") main_layout.addWidget(test_btn) # connection test_btn.clicked.connect(self.list_items) # function def list_items(self): print('hello in python, not shown in unity. - from TestQ') self.u_print('hello in unity. - from TestQ') obj_list = unity.Object.FindObjectsOfType(unity.GameObject) for each_obj in obj_list: self.u_print(each_obj.name) def u_print(self, info): unity.Debug.Log(info) # fix QApplication singleton issue for run python inside some app if not QtWidgets.QApplication.instance(): app = QtWidgets.QApplication([]) else: app = QtWidgets.QApplication.instance() main_ui = TestUI() main_ui.show()
viewport navigation | alt-based Mouse navigate, RMB-hold WASD key navigate |
---|---|
focus on selected | f |
snap obj to view pos | ctrl+shift+f (good for cam to cam match) |
max view | shift+space (like max) |
Customize view
asset panel | slide <left to list, >right to grid view |
Debug.Log("Current Index is " + index); public bool CamSwitch = true; [Header("Distance in meters")] [Tooltip("Tell the truth")] public float Distance; public float Radius; public int Counter; public Color NewColor; public string NewName; if (NewName!=null && NewName!=""){} if (char.IsLetter(NewName[0])) {} // first char is letter public enum Meal { Breakfast, Lunch, Dinner, Supper } int choice = (int)(MyMeal); public Vector3 MyVector; public Transform BulletEmiter; public Object BulletPrefab; public Light MyLight;
gameObject.name = "NewName"; transform.position = new Vector3(1,2,3); Camera myCam = GetComponent<Camera>(); myCam.fieldOfView = CameraFov; myCam.enabled = CamSwitch; Light cur_light = GetComponent<Light>(); cur_light.color = MyColor;
gameObject.GetComponent<Renderer>().material.color = Color.red; // for safe, better check GetComponent return not null if (compo != null){}
Destroy(gameObject, life); // delete object after life seconds
// opt check require for rigid body [RequireComponent(typeof(Rigidbody))] void Start(){ // set initial speed after born Rigidbody rb = GetComponent<Rigidbody>(); rb.velocity = transform.forward * BulletSpeed; } void FixedUpdate(){ // before physics float vertical = Input.GetAxis("Vertical"); float horizontal = Input.GetAxis("Horizontal"); //this is inside FixedUpdate, so we use Time.fixedDeltaTime float deltaTime = Time.fixedDeltaTime; Quaternion rotationDelta = Quaternion.Euler(0, TurnRate * horizontal * deltaTime, 0); Quaternion newRotation = rb.rotation * rotationDelta; rb.rotation = newRotation; Vector3 forward = rb.rotation * Vector3.forward; Vector3 moveDelta = forward * Speed * vertical * deltaTime; Vector3 newPos = rb.position + moveDelta; rb.position = newPos; } void Update() { float dist = Time.deltaTime * speed; transform.Translate(0, 0, dist); //if (Input.GetKeyDown(KeyCode.Space)) if (Input.GetButtonDown("Fire1") && BulletPrefab!=null) { Instantiate(BulletPrefab, BulletEmiter.position, BulletEmiter.rotation); } //transform.Rotate(0, Time.deltaTime * speed, 0); float turn_amount_h = Time.deltaTime * RotateSpeed * Input.GetAxis("GunHorizontal"); float turn_amount_v = Time.deltaTime * RotateSpeed * Input.GetAxis("GunVertical"); transform.Rotate(turn_amount_v, turn_amount_h, 0); float turn_amount = Time.deltaTime * RotateSpeed * Input.GetAxis("Horizontal"); float forward_dist = Time.deltaTime * speed * Input.GetAxis("Vertical"); //transform.Translate(x_dist, 0, y_dist); transform.Rotate(0, turn_amount, 0); transform.Translate(0, 0, forward_dist); bool jump_start = Input.GetKeyDown(KeyCode.Space); bool jump_end = Input.GetKeyUp(KeyCode.Space); bool flying = Input.GetKey(KeyCode.Space); if (Input.GetKeyDown(KeyCode.W)) { print("Wave~~~~~"); } if (Input.GetKeyDown(KeyCode.H) ) { if ((Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl))) { print("Help NOW!!!"); } else { print("Need a help."); } } }
Input.GetAxis() // "Horizontal" and "Vertical": mapped to joystick, A, W, S, D and the arrow keys // "Mouse X" and "Mouse Y" : mapped to the mouse delta. // "Fire1", "Fire2" "Fire3" are mapped to Ctrl, Alt, Cmd keys and three mouse or joystick buttons // for any kind of movement behaviour use Input.GetButton() for action-like events only //all the Input calls in the Update Loop. KeyCode : all of the key press, mouse and joystick options. Input.touches : mobile Input.acceleration & Input.deviceOrientation: device orientation in three-dimensional space -property Input.anyKey: any key been holding Input.anyKeyDown: the first frame the user hits any key or mouse button Input.mousePosition: current mouse position in pixel coordinates -method() Input.GetAxis(): value of the virtual axis identified by axisName Input.GetButton(): button been hold down? Input.GetButtonDown(): the frame the user pressed down the virtual button? Input.GetButtonUp(): first frame the user releases the virtual button? Input.GetMouseButton(): the given mouse button is held down? Input.GetMouseButtonDown(): the frame the user pressed the given mouse button? Input. GetMouseButtonUp(): the frame the user releases the given mouse button? Input.GetTouch(): return touch info Input.GetJoystickNames(): Retrieves a list of input device names Input.GetKey(KeyCode.Space): user holds down the key? (space key example) Input.GetKeyDown(): the frame the user starts pressing down the key? Input.GetKeyUp(): the frame the user releases the key? if (Input.GetMouseButtonDown(0)){} // 0 - left button; 1 - right button; 2 - middle button
private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Wall")) { print("I hit a wall"); } //Destroy(collision.gameObject); // destroy target when it hit Destroy(gameObject);//destroy the bullet when it hit something }
//require to access SceneManager using UnityEngine.SceneManagement; SceneManager.LoadScene(SceneName);