Welcome to PyUnity’s documentation!¶
Version 0.8.4 (in development)¶
PyUnity is a pure Python 3D Game Engine that was inspired by the structure of the Unity Game Engine. This does not mean that PyUnity are bindings for the UnityEngine. However, this project has been made to facilitate any programmer, beginner or advanced, novice or veteran.
Disclaimer¶
As we have said above, this is not a set of bindings for the UnityEngine, but a pure Python library to aid in making 3D games in Python.
Installing¶
To install PyUnity for Linux distributions based on Ubuntu or Debian, use:
> pip3 install pyunity
To install PyUnity for other operating systems, use pip:
> pip install pyunity
Alternatively, you can clone the repository to build the package from source. The latest version is on the master branch and you can build as follows:
> git clone https://github.com/pyunity/pyunity
> git checkout master
> python setup.py install
The latest builds are on the develop
branch
which is the default branch. These builds are
sometimes broken, so use at your own risk.
> git clone https://github.com/pyunity/pyunity
> python setup.py install
Its only dependencies are PyOpenGL, PySDL2, GLFW, Pillow and PyGLM. Microsoft Visual C++ Build Tools are required on Windows for building yourself.
Links¶
For more information check out the API Documentation.
If you would like to contribute, please first see the contributing guidelines, check out the latest issues and make a pull request.
Releases¶
v0.8.2¶
Bugfix regarding Quaternion.FromDir
, Quaternion.Euler
,
abstractmethod
and 2D depth buffers.
v0.8.1¶
Bugfix regarding camera position updating and input axes.
v0.8.0¶
New features:
- Rewrote documentation and docstrings
- Reformatted code
- F string integration
ImmutableStruct
andABCMeta
metaclasses- The
ABCMeta
class has more features than the default Pythonabc
module.
- The
- Rewrote examples
- Combined many functions common to both Vector2 and Vector3 into a single Vector class.
- If you want to implement your own Vector classes, subclass from Vector and implement the required abstract methods.
- Fixed quaternion and rotation maths
- Input axes and mouse input
- Multiple lights
- Different light types
- Window provider caching and checking
- Gui components
- This includes buttons, checkboxes, images and text boxes
- Rect transforms can be very flexible
- Platform-specific font loading
- Stub package
- This will work with editors such as VSCode and PyCharm, just install
pyunity-stubs
from pip
- This will work with editors such as VSCode and PyCharm, just install
Stub package: https://pypi.org/project/pyunity-stubs
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.8.0
v0.7.1¶
Extra features used in the PyUnity Editor.
Changes:
- Code of Conduct and Contributing guides
- Rewrote most of the README to clear confusion about what PyUnity really is
- RGB and HSV
- Better GameObject deleting
- ShowInInspector and HideInInspector
- Dynamic lighting
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.7.1
v0.7.0¶
New features:
- Customizable skybox
- Editor integration
- Rewrote scene saving and loading
- PYUNITY_WINDOW_PROVIDER environment variable
- Fixed example 8
Editor GitHub: https://github.com/pyunity/pyunity-gui
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.7.0
v0.6.0¶
Project structure update.
New features:
- Replaced Pygame with PySDL2
- Revamped audio module
- Fixed input bugs
- Added scene saving
- Added project saving
- Added project structure
- Automated win32 builds on Appveyor
- Removed redundant code from fixed function pipeline
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.6.0
v0.5.2¶
Small minor fix of shader inclusion in binary distributions.
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.5.2
v0.5.1¶
Bugfix that fixes the shaders and dependency management.
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.5.1
v0.5.0¶
Big rendering update that completely rewrites rendering code and optimizes it.
New features:
- Script loading
- Shaders
- Vertex buffer objects and vertex array objects
- Optimized rendering
- Colours
- Textures
- New lighting system
- New meshes and mesh loading
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.5.0
v0.4.0¶
Small release that has large internal changes.
New features:
- Added logger
- Moved around files and classes to make it more pythonic
- Rewrote docs
- Fixed huge bug that broke all versions from 0.2.0-0.3.1
- Clarified README.md
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.4.0
v0.3.1¶
Bugfix on basically everything because 0.3.0 was messed up.
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.3.1
v0.3.0¶
After a long break, 0.3.0 is finally here!
New features:
- Added key input (not fully implemented)
- Fixed namespace pollution
- Fixed minor bugs
- Window resizing implemented
- New Scene loading interface
- Python 3.9 support
- Finished pxd files
- LGTM Integration
- AppVeyor is now the main builder
- Code is now PEP8-friendly
- Added tests.py
- Cleaned up working directory
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.3.0
v0.2.1¶
Small bugfix around the AudioClip loading and inclusion of the OGG file in example 8.
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.2.1
v0.2.0¶
A CI integration update, with automated building from Appveyor and Travis CI.
Features:
- Shaded faces with crisp colours
- PXD files to optimize Cython further (not yet implemented fully)
- Scene changing
- FPS changes
- Better error handling
- Travis CI and AppVeyor integration
- Simple audio handling
- Changelogs in the dist folder of master
- Releases branch for builds from Travis
- Python 3.6 support
- 1 more example, bringing the total to 8
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.2.0
v0.1.0¶
Cython update, where everything is cythonized. First big update.
Features:
- Much more optimized rendering with Cython
- A new example
- Primitives
- Scaling
- Tutorials
- New color theme for documentation
- Timer decorator
- Non-interactive mode
- Frustrum culling
- Overall optimization
Notes:
The FPS config will not have a change due to the inability of cyclic imports in Cython.
You can see the c code used in Cython in the src folder.
When installing with
setup.py
, you can set the environment variablea
to anything but an empty string, this will disable recreating the c files. For example:> set a=1 > python setup.py install
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.1.0
v0.0.5¶
Transform updates, with new features extending GameObject positioning.
Features:
- Local transform
- Quaternion
- Better example loader
- Primitive objects in files
- Fixed jittering when colliding from an angle
- Enabled friction (I don’t know when it was turned off)
- Remove scenes from SceneManager
- Vector division
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.0.5
v0.0.4¶
Physics update.
New features:
- Rigidbodies
- Gravity
- Forces
- Optimized collision
- Better documentation
- Primitive meshes
- PyUnity mesh files that are optimized for fast loading
- Pushed GLUT to the end of the list so that it has the least priority
- Fixed window loading
- Auto README.md updater
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.0.4
v0.0.3¶
More basic things added.
Features:
- Examples (5 of them!)
- Basic physics components
- Lighting
- Better window selection
- More debug options
- File loader for .obj files
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.0.3
v0.0.2¶
First proper release (v0.0.1 was lost).
Features:
- Documentation
- Meshes
Download source code at https://github.com/pyunity/pyunity/releases/tag/0.0.2
Tutorials¶
Here are some tutorials to get you started in using PyUnity. They need no prior knowledge about Unity, but they do require you to be comfortable with using Python.
Tutorial 1: The Basics¶
Table of Contents
In this tutorial you will be learning the basics to using PyUnity, and understanding some key concepts.
What is PyUnity?¶
PyUnity is a Python implementation of the UnityEngine, which was originally written in C++. PyUnity has been modified to be as easy to use in Python as possible, without sacrificing the flexibility and the versatilility of Unity.
Basic concepts¶
In PyUnity, everything belongs to a
GameObject
. A GameObject is a named
object that has lots of Components on it, each
affecting the GameObject and other GameObjects.
Components are Python objects that do a specific
job, like rendering an object or deleting other
GameObjects.
Transforms¶
Each GameObject has a special component called
a Transform
. A Transform holds information about
the GameObject’s position, rotation and scale.
A Transform also manages the hierarchy system in PyUnity.
Each transforms can have multiple children, which are all
Transforms attached to the children GameObjects.
All transforms will have a localPosition
, localRotation
and localScale
, which are all relative to their parent.
In addition, all Transforms will have a position
,
rotation
and scale
property which is measured
in global space.
For example, if there is a Transform at 1 unit up from
the origin, and its child had a localPosition
of
1 unit right, then the child would have a position
of
1 unit up and 1 unit to the right.
Code¶
All of that has now been established, so let’s start programing it all! To start, we need to import PyUnity.
>>> from pyunity import *
Loaded config
Trying GLFW as a window provider
GLFW doesn't work, trying PySDL2
Trying PySDL2 as a window provider
Using window provider PySDL2
Loaded PyUnity version 0.4.0
Note: the output beneath the import is debug info, you
can turn it off with the environment variable
PYUNITY_DEBUG_INFO
set to "0"
. For example:
>>> import os
>>> os.environ["PYUNITY_DEBUG_INFO"] = "0"
>>> from pyunity import *
>>> # No output
Now we’ve loaded the module, we can start creating our
GameObjects. To create a GameObject, use the GameObject
class:
>>> root = GameObject("Root")
Then we can change its position by accessing its transform.
All GameObjects have references to their transform by the
transform
attribute, and all components have a reference
to the GameObject and the Transform that they belong to, by
the gameObject
and transform
attributes. Here’s
how to make the GameObject positioned 1 unit up, 2 units to
the right and 3 units forward:
>>> root.transform.localPosition = Vector3(2, 1, 3)
A Vector3
is just a way to represent a 3D vector. In PyUnity
the coordinate system is a left-hand Y-axis up system, which
is essentially what OpenGL uses, but with the Z-axis flipped.
Then to add a child to the GameObject, specify the parent GameObject as the second argument:
>>> child1 = GameObject("Child1", root)
>>> child2 = GameObject("Child2", root)
Note: Accessing the localPosition
, localRotation
and
localScale
attributes are faster than using the position
,
rotation
and scale
properties. Use the local attributes
whenever you can.
Rotation¶
Rotation is measured in Quaternions. Do not worry about these, because they use some very complex maths. All you need to know are these methods:
- To make a Quaternion that represents no rotation, use
Quaternion.identity()
. This just means no rotation. - To make a Quaternion from an axis and angle, use the
Quaternion.FromAxis()
method. What this does is it creates a Quaternion that represents a rotation around an axis clockwise, byangle
degrees. The axis does not need to be normalized. - To make a Quaternion from Euler angles, use
Quaternion.Euler
. This creates a Quaternion from Euler angles, where it is rotated on the Z-axis first, then the X-axis, and finally the Y-axis.
Transforms also have localEulerAngles
and eulerAngles
properties, which just represent the Euler angles of the
rotation Quaternions. If you don’t know how Quaternions work, only use
the eulerAngles
property.
In the next tutorial, we’ll be covering how to render things and use a Scene.
Tutorial 2: Rendering in Scenes¶
Table of Contents
Last tutorial we covered some basic concepts on GameObjects and Transforms, and this time we’ll be looking at how to render things in a window.
Scenes¶
A Scene
is like a page to draw on: you can
add things, remove things and change things.
To create a scene, you can call
SceneManager.AddScene
:
>>> scene = SceneManager.AddScene("Scene")
In your newly created scene, you have 2 GameObjects: a Main Camera, and a Light. These two things can be moved around like normal GameObjects.
Next, let’s move the camera back 10 units:
>>> scene.mainCamera.transform.localPosition = Vector3(0, 0, -10)
scene.mainCamera
references the Camera
Component
on the Main Camera, so we can access the Transform
by using its transform
attribute.
Meshes¶
To render anything, we need a model of it. Let’s say we want to create a cube. Then we need a model of a cube, or what’s called a mesh. Meshes have 4 pieces of data: the vertices (or points), the faces, the normals and the texture coordinates. Normals are just vectors saying which way the face is pointing, and texture coordinates are coordinates to represent how an image is displayed on the surface of a mesh.
For a simple object like a cube, we don’t need to
create our own mesh. Fortunately there is a method
called Mesh.cube
which creates a cube for us.
Here it is:
>>> cubeMesh = Mesh.cube(2)
The 2
means to create a cube with side lengths of
2. Then, to render this mesh, we need a new Component.
The MeshRenderer¶
The MeshRenderer is a Component that can render a mesh
in the scene. To add a new Component, we can use
a method called AddComponent
:
>>> cube = GameObject("cube")
>>> renderer = cube.AddComponent(MeshRenderer)
Now we can give our renderer the cube mesh from before.
>>> renderer.mesh = cubeMesh
Finally, we need a Material
to use. To create a Material,
we need to specify a color in RGB
.
>>> renderer.mat = Material(RGB(255, 0, 0))
Here I used a red material. Finally we need to add the cube to our scene, otherwise we can’t see it in the window:
>>> scene.Add(cube)
The full code:
>>> from pyunity import *
Loaded config
Trying GLFW as a window provider
GLFW doesn't work, trying PySDL2
Trying PySDL2 as a window provider
Using window provider PySDL2
Loaded PyUnity version 0.4.0
>>> scene = SceneManager.AddScene("Scene")
>>> scene.mainCamera.transform.localPosition = Vector3(0, 0, -10)
>>> cubeMesh = Mesh.cube(2)
>>> cube = GameObject("Cube")
>>> renderer = cube.AddComponent(MeshRenderer)
>>> renderer.mesh = cubeMesh
>>> renderer.mat = Material(RGB(255, 0, 0))
>>> scene.Add(cube)
Then, to run our scene, we use SceneManager.LoadScene(scene)
. And now we have
a cube:
To see it better, let’s move the camera up a bit and tilt it downwards. Replace the third line with this:
>>> scene.mainCamera.transform.localPosition = Vector3(0, 3, -10)
>>> scene.mainCamera.transform.localEulerAngles = Vector3(15, 0, 0)
Now we can see it better:
Let’s say we want to place an image onto the cube. To do this,
we need to change the Material and add a Texture2D
.
>>> renderer.mat = Material(RGB(255, 255, 255), Texture2D("pyunity.png"))
Place pyunity.png
in the same folder as your script and run
the code. Here is the image for reference:
And here is the complete code:
from pyunity import *
scene = SceneManager.AddScene("Scene")
scene.mainCamera.transform.localPosition = Vector3(0, 0, -10)
cubeMesh = Mesh.cube(2)
cube = GameObject("Cube")
renderer = cube.AddComponent(MeshRenderer)
renderer.mesh = cubeMesh
renderer.mat = Material(RGB(255, 0, 0), Texture2D("pyunity.png"))
scene.Add(cube)
SceneManager.LoadScene(scene)
Debugging¶
If you want to see what you’ve done already, then you can use
a number of debugging methods. The first is to call scene.List()
:
>>> scene.List()
/Main Camera
/Light
/Cube
This lists all the Gameobjects in the scene. Then, let’s check the cube’s components:
>>> cube.components
[<Transform position=Vector3(0, 0, 0) rotation=Quaternion(1, 0, 0, 0) scale=Vector3(1, 1, 1) path="/Cube">, <pyunity.core.MeshRenderer object at 0x0B170CA0>]
Finally, let’s check the Main Camera’s transform.
>>> scene.mainCamera.transform
<Transform position=Vector3(0, 3, -10) rotation=Quaternion(0.9914448613738104, 0.13052619222005157, 0.0, 0.0) scale=Vector3(1, 1, 1) path="/Main Camera">
Next tutorial, we’ll be covering scripts and ``Behaviour``s.
Tutorial 3: Scripts and Behaviours¶
Table of Contents
Last tutorial we covered rendering meshes. In this tutorial we will be seeing how to make 2 GameObjects interact with each other.
Behaviours¶
A Behaviour
is a Component that you can create
yourself. To create a Behaviour, subclass from
it:
>>> class MyBehaviour(Behaviour):
... pass
In this case the Behaviour does nothing. To make it do something, use the Update function:
>>> class Rotator(Behaviour):
... def Update(self, dt):
... self.transform.localEulerAngles += Vector3(0, 90, 0) * dt
What this does is it rotates the GameObject that
the Behaviour is on by 90 degrees each second
around the y-axis. The Update
function takes
1 argument, dt
, which is how many seconds have
passed since the last frame.
Behaviours vs Components¶
Look at this watered-down version of the
Component
class:
class Component:
def __init__(self):
self.gameObject = None
self.transform = None
def GetComponent(self, component):
return self.gameObject.GetComponent(component)
def AddComponent(self, component):
return self.gameObject.AddComponent(component)
A Component has 2 attributes: gameObject
and transform
.
This is set whenever the Component is added to a GameObject.
A Behaviour is subclassed from a Component and so has the
same attributes. Each frame, the Scene will call the Update
function on all Behaviours, passing the time since the last
frame in seconds.
When you want to do something at the start of the Scene, use
the Start
function. That will be called right at the start
of the scene, when scene.Run()
is called.
>>> class MyBehaviour(Behaviour):
... def Start(self):
... self.a = 0
... def Update(self, dt):
... print(self.a)
... self.a += dt
The example above will print in seconds how long
it had been since the start of the Scene. Note
that the order in which all Behaviours’
Start
functions will be the orders of the
GameObjects.
With this, you can create all sorts of Components,
and because Behaviour is subclassed from
Component, you can add a Behaviour to a GameObject
with AddComponent
.
Examples¶
This creates a spinning cube:
>>> class Rotator(Behaviour):
... def Update(self, dt):
... self.transform.localEulerAngles += Vector3(0, 90, 135) * dt
...
>>> scene = SceneManager.AddScene("Scene")
>>> cube = GameObject("Cube")
>>> renderer = cube.AddComponent(MeshRenderer)
>>> renderer.mesh = Mesh.cube(2)
>>> renderer.mat = Material(RGB(255, 0, 0))
>>> cube.AddComponent(Rotator)
>>> scene.Add(cube)
>>> scene.Run()
This is a debugging Behaviour, which prints out the change in position, rotation and scale each 10 frames:
class Debugger(Behaviour):
lastPos = Vector3.zero()
lastRot = Quaternion.identity()
lastScl = Vector3.one()
a = 0
def Update(self, dt):
self.a += 1
if self.a == 10:
print(self.transform.position - self.lastPos)
print(self.transform.rotation.conjugate * self.lastRot)
print(self.transform.scale / self.lastScl)
self.a = 0
Note that the printed output for non-moving things would be as so:
Vector3(0, 0, 0)
Quaternion(1, 0, 0, 0)
Vector3(1, 1, 1)
Vector3(0, 0, 0)
Quaternion(1, 0, 0, 0)
Vector3(1, 1, 1)
Vector3(0, 0, 0)
Quaternion(1, 0, 0, 0)
Vector3(1, 1, 1)
...
This means no rotation, position or scale change.
It will break when you set the scale to
Vector3(0, 0, 0)
.
In the next tutorial we’ll be looking at 2D development.
Tutorial 4: 2D¶
Table of Contents
This tutorial we will be introducing many
new components, namely the RectTransform
and the Image2D
. There is more to
2D than this, but most of the tutorial is quite
dense in new ideas.
Data types¶
To facilitate positioning objects, we are
going to use RectAnchors
and
RectOffset
. They both subclass
RectData
, which means they have two
properties: min
and max
. They are both of
type Vector2
. For now, let’s ignore the
RectAnchors
.
RectOffset¶
By ignoring RectAnchors
we can simplify
our offset to a literal rectangle. The min
value
specifies the top left corner of the rectangle, and
the max
value specifies the bottom right corner.
In PyUnity, the X axis goes left to right and the Y
axis goes top to bottom.
For example, a rect that is 100 pixels by 150 pixels, with a top left corner of (50, 75) would be like this:
>>> offset = RectOffset(
... Vector2(50, 75),
... Vector2(150, 225) # 100 + 50 and 150 + 75
... )
RectTransform¶
A RectTransform
has 5 notable properties:
parent
, anchors
, offset
, rotation
and pivot
. parent
is a read-only property,
which gets the RectTransform
of its parent,
if it has one. rotation
is a
float measured in degrees, and pivot
is
a point between (0.0, 0.0) and (1.0, 1.0) which
defines the rotation point.
Image2D¶
A RectTransform
can’t really do much on its own,
so we’ll look at the Image2D
component. This
renders a texture in the rect that is defined from
the RectTransform
. If you read tutorial 2, you
may have used the Texture2D
class. Here we can
do the exact same:
>>> gameObject = GameObject("Image")
>>> transform = gameObject.AddComponent(RectTransform)
>>> transform.offset = RectOffset.Rectangle(
... Vector2(100, 100), center=Vector2(125, 75))
>>> img = gameObject.AddComponent(Image2D)
>>> img.texture = Texture2D("python.png")
Canvas¶
All 2D renderers must be a descendant of a Canvas
element, which can customize the rendering of 2D
components. We don’t need to worry about that too much,
except that if we were to create an Image2D
we must
make it as a child or descendant of our canvas.
canvas = GameObject("Canvas")
canvas.AddComponent(Canvas)
img = GameObject("Image", canvas)
# And so on...
Here the second argument to the GameObject
constructor
specifies its parent, which must be a GameObject
.
Code¶
from pyunity import *
scene = SceneManager.AddScene("Scene")
canvas = GameObject("Canvas")
canvas.AddComponent(Canvas)
scene.Add(canvas)
gameObject = GameObject("Image", canvas)
transform = gameObject.AddComponent(RectTransform)
transform.offset = RectOffset.Rectangle(
Vector2(100, 100), center=Vector2(125, 75))
img = gameObject.AddComponent(Image2D)
img.texture = Texture2D("pyunity.png")
scene.Add(gameObject)
SceneManager.LoadScene(scene)
PyUnity image:
This is the result:
Interaction¶
The easiest way to create an interactable image
is to use the Button
class. This will trigger
whenever any part of the rect is clicked on. Here
is an example:
def callback():
print("Clicked")
# Same canvas and image code as above
...
button = gameObject.AddComponent(Button)
button.callback = callback
If you check the docs for the Button
class,
you can see two more attributes: state
and
button
. This specifies what state and which
button must be pressed for the callback to trigger.
If you would like more control over the button, using a Behaviour is easier as it can interact easily with other GameObjects and is created on a per-component basis. However, if you would like more interaction with the mouse, here is a method:
class HoverUpdater(Behaviour, GuiComponent):
def HoverUpdate(self):
print("Hovering over component")
# Same canvas and image code as above
...
gameObject.AddComponent(HoverUpdater)
The GuiComponent
class defines an abstract method
called HoverUpdate
which is called whenever the mouse
is hovering over a component. This method will be called
exactly once per canvas in a single GuiComponent each frame.
In fact, this is how the Button
class is implemented.
Anchors¶
For a 2D rect to scale with the window, we can use the
anchors
property of the RectTransform
. This has
two values like the offset
, a min
and a max
.
These two values are between Vector2(0, 0)
and
Vector2(1, 1)
, where 0 and 1 represent the left and
right of the window, or the top and bottom of the window.
The offsets are applied where the anchors are.
The easiest way to understand this is when the anchors are
a single point. For example, the default anchors are
RectAnchors(Vector2(0, 0), Vector2(0, 0))
. This means
both points of the anchors are at Vector2(0, 0)
so
all offsets are calculated from the top left.
If we wanted our rect to be centered in the middle at all
times, or be offset from the middle, we can set the anchors
to be at Vector2(0.5, 0.5)
. Likewise, if we wanted our
rect to be at the bottom right, we can use Vector2(1, 1)
.
This applies with two anchors: if we wanted our rect to be 50px
away from the edges of the window, we would use anchors of
RectAnchors(Vector2(0, 0), Vector2(1, 1))
and offset of
RectOffset(Vector2(50, 50), Vector2(-50, -50))
. This is how
we can control the scaling of a rect with respect to the window size.
This tutorial was quite code-heavy, and it is not quite complete. If you are confused, please join our discord support server at https://discord.com/zTn48BEbF9.
Links¶
Here are some links to websites about the PyUnity project:
https://github.com/pyunity/pyunity - GitHub repository
https://pypi.org/project/pyunity - PyPi page
https://discord.gg/zTn48BEbF9 - Discord server
License¶
MIT License
Copyright (c) 2020-2021 Ray Chen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
API Documentation¶
Information on specific functions, classes, and methods.
Subpackages¶
pyunity.physics package¶
Submodules¶
-
pyunity.physics.config.
gravity
= Vector3(0, -9.81, 0)¶ Gravitational constant (9.81 m/s^2)
Core classes of the PyUnity physics engine.
-
pyunity.physics.core.
Infinity
= inf¶ A representation of infinity
-
class
pyunity.physics.core.
PhysicMaterial
(restitution=0.75, friction=1, immutable=False)[source]¶ Bases:
object
Class to store data on a collider’s material. :param restitution: Bounciness of the material :type restitution: float :param friction: Friction of the material :type friction: float
-
class
pyunity.physics.core.
Manifold
(a, b, normal, penetration)[source]¶ Bases:
object
Class to store collision data. :param a: The first collider :type a: Collider :param b: The second collider :type b: Collider :param normal: The collision normal :type normal: Vector3 :param penetration: How much the two colliders overlap :type penetration: float
-
class
pyunity.physics.core.
Collider
(transform)[source]¶ Bases:
pyunity.core.Component
Collider base class.
-
pos
¶
-
-
class
pyunity.physics.core.
SphereCollider
(transform)[source]¶ Bases:
pyunity.physics.core.Collider
A spherical collider that cannot be deformed.
-
collidingWith
(other)[source]¶ Check to see if the collider is colliding with another collider.
Parameters: other (Collider) – Other collider to check against Returns: Collision data Return type: Manifold or None Notes
To check against another SphereCollider, the distance and the sum of the radii is checked. To check against an AABBoxColider, the check is as follows: 1. The sphere’s center is checked to see if it
is inside the AABB.- If it is, then the two are colliding.
- If it isn’t, then a copy of the position is clamped to the AABB’s bounds.
- Finally, the distance between the clamped position and the original position is measured.
- If the distance is bigger than the sphere’s radius, then the two are colliding.
- If not, then they aren’t colliding.
-
-
class
pyunity.physics.core.
AABBoxCollider
(transform)[source]¶ Bases:
pyunity.physics.core.Collider
An axis-aligned box collider that cannot be deformed.
-
collidingWith
(other)[source]¶ Check to see if the collider is colliding with another collider.
Parameters: other (Collider) – Other collider to check against Returns: Collision data Return type: Manifold or None Notes
To check against another AABBoxCollider, the corners are checked to see if they are inside the other collider.
To check against a SphereCollider, the check is as follows: 1. The sphere’s center is checked to see if it
is inside the AABB.- If it is, then the two are colliding.
- If it isn’t, then a copy of the position is clamped to the AABB’s bounds.
- Finally, the distance between the clamped position and the original position is measured.
- If the distance is bigger than the sphere’s radius, then the two are colliding.
- If not, then they aren’t colliding.
-
-
class
pyunity.physics.core.
Rigidbody
(transform, dummy=False)[source]¶ Bases:
pyunity.core.Component
Class to let a GameObject follow physics rules.
-
physicMaterial
¶ Physics material of the Rigidbody
Type: PhysicMaterial
-
Move
(dt)[source]¶ Moves all colliders on the GameObject by the Rigidbody’s velocity times the delta time. :param dt: Time to simulate movement by :type dt: float
-
-
class
pyunity.physics.core.
CollManager
[source]¶ Bases:
object
Manages the collisions between all colliders. .. attribute:: rigidbodies
Dictionary of rigidbodies andthe colliders on the gameObject that the Rigidbody belongs to
type: dict -
dummyRigidbody
¶ A dummy rigidbody used when a GameObject has colliders but no rigidbody. It has infinite mass
Type: Rigidbody
-
AddPhysicsInfo
(scene)[source]¶ Get all colliders and rigidbodies from a specified scene. This overwrites the collider and rigidbody lists, and so can be called whenever a new collider or rigidbody is added or removed. :param scene: Scene to search for physics info :type scene: Scene
Notes
This function will overwrite the pre-existing dictionary of rigidbodies. When there are colliders but no rigidbody is on the GameObject, then they are placed in the dictionary with a dummy Rigidbody that has infinite mass and a default physic material. Thus, they cannot move.
-
GetRestitution
(a, b)[source]¶ Get the restitution needed for two rigidbodies, based on their combine function :param a: Rigidbody 1 :type a: Rigidbody :param b: Rigidbody 2 :type b: Rigidbody
Returns: Restitution Return type: float
-
Module contents¶
A basic 3D Physics engine that uses similar concepts to the Unity Engine itself. Only supports non-rotated colliders.
To create an immoveable object, use
math.inf or the provided Infinity
variable. This will make the object
not be able to move, unless you set
an initial velocity. Then, the
collider will either push everything
it collides with, or bounces it back
at twice the speed.
Example
>>> cube = GameObject("Cube")
>>> collider = cube.AddComponent(AABBoxCollider)
>>> collider.velocity = Vector3.right()
If you want to change some configurations, import the config file like so:
>>> from pyunity.physics import config
Inside the config file there are some configurations:
gravity
is the gravity of the whole system. It only affects Rigidbodies that haveRigidbody.gravity
set to True.
pyunity.scenes package¶
Submodules¶
Class to load, render and manage GameObjects and their various components.
You should never use the Scene
class directly, instead, only use
the SceneManager
class.
-
class
pyunity.scenes.scene.
Scene
(name)[source]¶ Bases:
object
Class to hold all of the GameObjects, and to run the whole scene.
Parameters: name (str) – Name of the scene Notes
Create a scene using the SceneManager, and don’t create a scene directly using this class.
-
static
Bare
(name)[source]¶ Create a bare scene.
Parameters: name (str) – Name of the scene Returns: A bare scene with no GameObjects Return type: Scene
-
rootGameObjects
¶ All GameObjects which have no parent
-
Add
(gameObject)[source]¶ Add a GameObject to the scene.
Parameters: gameObject (GameObject) – The GameObject to add.
-
Remove
(gameObject)[source]¶ Remove a GameObject from the scene.
Parameters: gameObject (GameObject) – GameObject to remove. Raises: PyUnityException
– If the specified GameObject is not part of the Scene.
-
Has
(gameObject)[source]¶ Check if a GameObject is in the scene.
Parameters: gameObject (GameObject) – Query GameObject Returns: If the GameObject exists in the scene Return type: bool
-
RegisterLight
(light)[source]¶ Register a light for the scene.
Parameters: light (Light) – Light component to register
-
FindGameObjectsByName
(name)[source]¶ Finds all GameObjects matching the specified name.
Parameters: name (str) – Name of the GameObject Returns: List of the matching GameObjects Return type: list
-
FindGameObjectsByTagName
(name)[source]¶ Finds all GameObjects with the specified tag name.
Parameters: name (str) – Name of the tag Returns: List of matching GameObjects Return type: list Raises: GameObjectException
– When there is no tag named name
-
FindGameObjectsByTagNumber
(num)[source]¶ Gets all GameObjects with a tag of tag num.
Parameters: num (int) – Index of the tag Returns: List of matching GameObjects Return type: list Raises: GameObjectException
– If there is no tag with specified index.
-
FindComponentByType
(component)[source]¶ Finds the first matching Component that is in the Scene.
Parameters: component (type) – Component type Returns: The matching Component Return type: Component Raises: ComponentException
– If the component is not found
-
FindComponentsByType
(component)[source]¶ Finds all matching Components that are in the Scene.
Parameters: component (type) – Component type Returns: List of the matching Components Return type: list
-
inside_frustrum
(renderer)[source]¶ Check if the renderer’s mesh can be seen by the main camera.
Parameters: renderer (MeshRenderer) – Renderer to test Returns: If the mesh can be seen Return type: bool
-
static
Module that manages creation and deletion of Scenes.
-
pyunity.scenes.sceneManager.
AddScene
(sceneName)[source]¶ Add a scene to the SceneManager. Pass in a scene name to create a scene.
Parameters: sceneName (str) – Name of the scene Returns: Newly created scene Return type: Scene Raises: PyUnityException
– If there already exists a scene called sceneName
-
pyunity.scenes.sceneManager.
AddBareScene
(sceneName)[source]¶ Add a scene to the SceneManager. Pass in a scene name to create a scene.
Parameters: sceneName (str) – Name of the scene Returns: Newly created scene Return type: Scene Raises: PyUnityException
– If there already exists a scene called sceneName
-
pyunity.scenes.sceneManager.
GetSceneByIndex
(index)[source]¶ Get a scene by its index.
Parameters: index (int) – Index of the scene Returns: Specified scene at index index Return type: Scene Raises: IndexError
– If there is no scene at the specified index
-
pyunity.scenes.sceneManager.
GetSceneByName
(name)[source]¶ Get a scene by its name.
Parameters: name (str) – Name of the scene Returns: Specified scene with name of name Return type: Scene Raises: KeyError
– If there is no scene called name
-
pyunity.scenes.sceneManager.
RemoveScene
(scene)[source]¶ Removes a scene from the SceneManager.
Parameters: scene (Scene) – Scene to remove
Raises: TypeError
– If the provided scene is not type ScenePyUnityException
– If the scene is not part of the SceneManager
-
pyunity.scenes.sceneManager.
LoadSceneByName
(name)[source]¶ Loads a scene by its name.
Parameters: name (str) – Name of the scene
Raises: TypeError
– When the provided name is not a stringPyUnityException
– When there is no scene namedname
-
pyunity.scenes.sceneManager.
LoadSceneByIndex
(index)[source]¶ Loads a scene by its index of when it was added to the SceneManager.
Parameters: index (int) – Index of the scene
Raises: TypeError
– When the provided index is not an integerPyUnityException
– When there is no scene at indexindex
-
pyunity.scenes.sceneManager.
LoadScene
(scene)[source]¶ Load a scene by a reference.
Parameters: scene (Scene) – Scene to be loaded
Raises: TypeError
– When the scene is not of type ScenePyUnityException
– When the scene is not part of the SceneManager. This is checked because the SceneManager has to make some checks before the scene can be run.
Module contents¶
Module to create and load Scenes.
pyunity.values package¶
Submodules¶
Class to represent a rotation in 3D space.
-
class
pyunity.values.quaternion.
Quaternion
(w, x, y, z)[source]¶ Bases:
object
Class to represent a unit quaternion, also known as a versor.
Parameters: -
copy
()[source]¶ Deep copy of the Quaternion.
Returns: A deep copy Return type: Quaternion
-
normalized
()[source]¶ A normalized Quaternion, for rotations. If the length is 0, then the identity quaternion is returned.
Returns: A unit quaternion Return type: Quaternion
-
conjugate
¶ The conjugate of a unit quaternion
-
angleAxisPair
¶ Gets or sets the angle and axis pair. Tuple of form (angle, axis).
-
static
Euler
(vector)[source]¶ Create a quaternion using Euler rotations.
Parameters: vector (Vector3) – Euler rotations Returns: Generated quaternion Return type: Quaternion
-
eulerAngles
¶ Gets or sets the Euler Angles of the quaternion
-
-
class
pyunity.values.texture.
Material
(color, texture=None)[source]¶ Bases:
object
Class to hold data on a material.
-
class
pyunity.values.texture.
RGB
(r, g, b)[source]¶ Bases:
pyunity.values.texture.Color
A class to represent an RGB color.
Parameters:
-
class
pyunity.values.vector.
Vector2
(x_or_list=None, y=None)[source]¶ Bases:
pyunity.values.vector.Vector
-
get_length_sqrd
()[source]¶ Gets the length of the vector squared. This is much faster than finding the length.
Returns: The length of the vector squared Return type: float
-
length
¶ Gets or sets the magnitude of the vector
-
normalized
()[source]¶ Get a normalized copy of the vector, or Vector2(0, 0) if the length is 0.
Returns: A normalized vector Return type: Vector2
-
normalize_return_length
()[source]¶ Normalize the vector and return its length before the normalization
Returns: The length before the normalization Return type: float
-
get_distance
(other)[source]¶ The distance between this vector and the other vector
Returns: The distance Return type: float
-
get_dist_sqrd
(other)[source]¶ The distance between this vector and the other vector, squared. It is more efficient to call this than to call get_distance and square it.
Returns: The squared distance Return type: float
-
int_tuple
¶ Return the x, y and z values of this vector as ints
-
rounded
¶ Return the x, y and z values of this vector rounded to the nearest integer
-
clamp
(min, max)[source]¶ Clamps a vector between two other vectors, resulting in the vector being as close to the edge of a bounding box created as possible.
Parameters:
-
dot
(other)[source]¶ Dot product of two vectors.
Parameters: other (Vector2) – Other vector Returns: Dot product of the two vectors Return type: float
-
-
class
pyunity.values.vector.
Vector3
(x_or_list=None, y=None, z=None)[source]¶ Bases:
pyunity.values.vector.Vector
-
copy
()[source]¶ Makes a copy of the Vector3
Returns: A shallow copy of the vector Return type: Vector3
-
get_length_sqrd
()[source]¶ Gets the length of the vector squared. This is much faster than finding the length.
Returns: The length of the vector squared Return type: float
-
length
¶ Gets or sets the magnitude of the vector
-
normalized
()[source]¶ Get a normalized copy of the vector, or Vector3(0, 0, 0) if the length is 0.
Returns: A normalized vector Return type: Vector3
-
normalize_return_length
()[source]¶ Normalize the vector and return its length before the normalization
Returns: The length before the normalization Return type: float
-
get_distance
(other)[source]¶ The distance between this vector and the other vector
Returns: The distance Return type: float
-
get_dist_sqrd
(other)[source]¶ The distance between this vector and the other vector, squared. It is more efficient to call this than to call get_distance and square it.
Returns: The squared distance Return type: float
-
int_tuple
¶ Return the x, y and z values of this vector as ints
-
rounded
¶ Return the x, y and z values of this vector rounded to the nearest integer
-
clamp
(min, max)[source]¶ Clamps a vector between two other vectors, resulting in the vector being as close to the edge of a bounding box created as possible.
Parameters:
-
dot
(other)[source]¶ Dot product of two vectors.
Parameters: other (Vector3) – Other vector Returns: Dot product of the two vectors Return type: float
-
Module contents¶
pyunity.window package¶
Submodules¶
Class to create a window using GLFW.
-
class
pyunity.window.glfwWindow.
Window
(name, resize)[source]¶ Bases:
pyunity.window.ABCWindow
A window provider that uses GLFW.
Raises: PyUnityException
– If the window creation fails
Class to create a window using FreeGLUT.
-
class
pyunity.window.glutWindow.
Window
(name, resize)[source]¶ Bases:
pyunity.window.ABCWindow
A window provider that uses FreeGLUT.
Class to create a window using PySDL2.
-
class
pyunity.window.sdl2Window.
Window
(name, resize)[source]¶ Bases:
pyunity.window.ABCWindow
A window provider that uses PySDL2.
Template window provider, use this for creating new window providers
Module contents¶
A module used to load the window providers.
The window is provided by one of three providers: GLFW, PySDL2 and GLUT. When you first import PyUnity, it checks to see if any of the three providers work. The testing order is as above, so GLUT is tested last.
To create your own provider, create a class that has the following methods:
__init__
: initiate your window and- check to see if it works.
start
: start the main loop in your- window. The first parameter is
update_func
, which is called when you want to do the OpenGL calls.
Check the source code of any of the window providers for an example. If you have a window provider, then please create a new pull request.
Submodules¶
pyunity.audio module¶
Classes to manage the playback of audio.
It uses the sdl2.sdlmixer library.
A variable in the config
module called
audio
will be set to False
if the
mixer module cannot be initialized.
-
pyunity.audio.
mixer
¶
-
class
pyunity.audio.
AudioClip
(path)[source]¶ Bases:
object
Class to store information about an audio file.
-
music
¶ Sound chunk that can be played with an SDL2 Mixer Channel. Only set when the AudioClip is played in an
AudioSource
.Type: sdl2.sdlmixer.mixer.Mix_Chunk
-
-
class
pyunity.audio.
AudioSource
(transform)[source]¶ Bases:
pyunity.core.Component
Manages playback on an AudioSource.
-
SetClip
(clip)[source]¶ Sets a clip for the AudioSource to play.
Parameters: clip (AudioClip) – AudioClip to play
-
Playing
¶ Gets if the AudioSource is playing.
-
-
class
pyunity.audio.
AudioListener
(transform)[source]¶ Bases:
pyunity.core.Component
Class to receive audio events and to base spatial sound from. By default the Main Camera has an AudioListener, but you can also remove it and add a new one to another GameObject in a Scene. There can only be one AudioListener, otherwise sound is disabled.
pyunity.core module¶
Core classes for the PyUnity library.
This module has some key classes used throughout PyUnity, and have to be in the same file due to references both ways. Usually when you create a scene, you should never create Components directly, instead add them with AddComponent.
Example
To create a GameObject with 2 children, one of which has its own child, and all have MeshRenderers:
>>> from pyunity import * # Import
Loaded config
Trying GLFW as a window provider
GLFW doesn't work, trying PySDL2
Trying PySDL2 as a window provider
Using window provider PySDL2
Loaded PyUnity version 0.8.4
>>> mat = Material(RGB(255, 0, 0)) # Create a default material
>>> root = GameObject("Root") # Create a root GameObjects
>>> child1 = GameObject("Child1", root) # Create a child
>>> child1.transform.localPosition = Vector3(-2, 0, 0) # Move the child
>>> renderer = child1.AddComponent(MeshRenderer) # Add a renderer
>>> renderer.mat = mat # Add a material
>>> renderer.mesh = Mesh.cube(2) # Add a mesh
>>> child2 = GameObject("Child2", root) # Create another child
>>> renderer = child2.AddComponent(MeshRenderer) # Add a renderer
>>> renderer.mat = mat # Add a material
>>> renderer.mesh = Mesh.quad(1) # Add a mesh
>>> grandchild = GameObject("Grandchild", child2) # Add a grandchild
>>> grandchild.transform.localPosition = Vector3(0, 5, 0) # Move the grandchild
>>> renderer = grandchild.AddComponent(MeshRenderer) # Add a renderer
>>> renderer.mat = mat # Add a material
>>> renderer.mesh = Mesh.cube(3) # Add a mesh
>>> root.transform.List() # List all GameObjects
/Root
/Root/Child1
/Root/Child2
/Root/Child2/Grandchild
>>> child1.components # List child1's components
[<Transform position=Vector3(-2, 0, 0) rotation=Quaternion(1, 0, 0, 0) scale=Vector3(1, 1, 1) path="/Root/Child1">, <pyunity.core.MeshRenderer object at 0x0A929460>]
>>> child2.transform.children # List child2's children
[<Transform position=Vector3(0, 5, 0) rotation=Quaternion(1, 0, 0, 0) scale=Vector3(1, 1, 1) path="/Root/Child2/Grandchild">]
-
class
pyunity.core.
Tag
(tagNumOrName)[source]¶ Bases:
object
Class to group GameObjects together without referencing the tags.
Parameters: Raises: ValueError
– If there is no tag nameIndexError
– If there is no tag at the provided indexTypeError
– If the argument is not a str or int
-
class
pyunity.core.
GameObject
(name='GameObject', parent=None)[source]¶ Bases:
object
Class to create a GameObject, which is an object with components.
Parameters: - name (str, optional) – Name of GameObject
- parent (GameObject or None) – Parent of GameObject
-
static
BareObject
(name='GameObject')[source]¶ Create a bare GameObject with no components or attributes.
Parameters: name (str) – Name of the GameObject
-
AddComponent
(componentClass)[source]¶ Adds a component to the GameObject. If it is a transform, set GameObject’s transform to it.
Parameters: componentClass (Component) – Component to add. Must inherit from Component
-
GetComponent
(componentClass)[source]¶ Gets a component from the GameObject. Will return first match. For all matches, use GetComponents.
Parameters: componentClass (Component) – Component to get. Must inherit from Component
Returns: The specified component, or None if the component is not found Return type: Component or None
-
RemoveComponent
(componentClass)[source]¶ Removes the first matching component from a GameObject.
Parameters: componentClass (type) – Component to remove
Raises: ComponentException
– If the GameObject doesn’t have the specified componentComponentException
– If the specified component is a Transform
-
class
pyunity.core.
HideInInspector
(type=None, default=None)[source]¶ Bases:
object
An attribute that should be saved when saving a project, but not shown in the Inspector of the PyUnityEditor.
-
default
¶ Default value (will be set to the Behaviour)
Type: Any
-
name
¶ None
Type: NoneType
-
-
class
pyunity.core.
ShowInInspector
(type=None, default=None, name=None)[source]¶ Bases:
pyunity.core.HideInInspector
An attribute that should be saved when saving a project, and shown in the Inspector of the PyUnityEditor.
-
default
¶ Default value (will be set to the Behaviour)
Type: Any
-
-
class
pyunity.core.
Component
(transform, is_dummy=False)[source]¶ Bases:
object
Base class for built-in components.
-
gameObject
¶ GameObject that the component belongs to.
Type: GameObject
-
AddComponent
(component)[source]¶ Calls AddComponent on the component’s GameObject.
Parameters: component (Component) – Component to add. Must inherit from Component
-
GetComponent
(component)[source]¶ Calls GetComponent on the component’s GameObject.
Parameters: componentClass (Component) – Component to get. Must inherit from Component
-
RemoveComponent
(component)[source]¶ Calls RemoveComponent on the component’s GameObject.
Parameters: component (Component) – Component to remove. Must inherit from Component
-
GetComponents
(component)[source]¶ Calls GetComponents on the component’s GameObject.
Parameters: componentClass (Component) – Component to get. Must inherit from Component
-
RemoveComponents
(component)[source]¶ Calls RemoveComponents on the component’s GameObject.
Parameters: component (Component) – Component to remove. Must inherit from Component
-
scene
¶ Get either the scene of the GameObject or the current running scene.
-
-
class
pyunity.core.
SingleComponent
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.Component
Represents a component that can be added only once.
-
class
pyunity.core.
Transform
(transform=None)[source]¶ Bases:
pyunity.core.SingleComponent
Class to hold data about a GameObject’s transformation.
-
gameObject
¶ GameObject that the component belongs to.
Type: GameObject
-
localRotation
¶ Rotation of the Transform in local space.
Type: Quaternion
-
parent
¶ Parent of the Transform. The hierarchical tree is actually formed by the Transform, not the GameObject. Do not modify this attribute.
Type: Transform or None
-
position
¶ Position of the Transform in world space.
-
rotation
¶ Rotation of the Transform in world space.
-
localEulerAngles
¶ Rotation of the Transform in local space. It is measured in degrees around x, y, and z.
-
eulerAngles
¶ Rotation of the Transform in world space. It is measured in degrees around x, y, and z.
-
scale
¶ Scale of the Transform in world space.
-
ReparentTo
(parent)[source]¶ Reparent a Transform.
Parameters: parent (Transform) – The parent to reparent to.
-
List
()[source]¶ Prints the Transform’s full path from the root, then lists the children in alphabetical order. This results in a nice list of all GameObjects.
-
FullPath
()[source]¶ Gets the full path of the Transform.
Returns: The full path of the Transform. Return type: str
-
LookAtTransform
(transform)[source]¶ Face towards another transform’s position.
Parameters: transform (Transform) – Transform to face towards Notes
The rotation generated may not be upright, and to fix this just use
transform.rotation.eulerAngles *= Vector3(1, 1, 0)
which will remove the Z component of the Euler angles.
-
LookAtGameObject
(gameObject)[source]¶ Face towards another GameObject’s position. See Transform.LookAtTransform for details.
Parameters: gameObject (GameObject) – GameObject to face towards
-
-
class
pyunity.core.
LightType
[source]¶ Bases:
enum.IntEnum
An enumeration.
-
Point
= 0¶
-
Directional
= 1¶
-
Spot
= 2¶
-
-
class
pyunity.core.
Light
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.SingleComponent
Component to hold data about the light in a scene.
-
type
= 1
-
-
class
pyunity.core.
MeshRenderer
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.SingleComponent
Component to render a mesh at the position of a transform.
pyunity.errors module¶
Module for all exceptions and warnings related to PyUnity.
-
exception
pyunity.errors.
PyUnityException
[source]¶ Bases:
Exception
Base class for PyUnity exceptions.
-
exception
pyunity.errors.
ComponentException
[source]¶ Bases:
pyunity.errors.PyUnityException
Class for PyUnity exceptions relating to components.
-
exception
pyunity.errors.
GameObjectException
[source]¶ Bases:
pyunity.errors.PyUnityException
Class for PyUnity exceptions relating to GameObjects.
pyunity.files module¶
Module to load files and scripts. Also manages project structure.
-
pyunity.files.
convert
(type, list)[source]¶ Converts a Python array to a C type from
ctypes
.Parameters: - type (_ctypes.PyCSimpleType) – Type to cast to.
- list (list) – List to cast
Returns: A C array
Return type:
-
class
pyunity.files.
Behaviour
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.Component
Base class for behaviours that can be scripted.
-
gameObject
¶ GameObject that the component belongs to.
Type: GameObject
-
Update
(dt)[source]¶ Called every frame.
Parameters: dt (float) – Time since last frame, sent by the scene that the Behaviour is in.
-
-
class
pyunity.files.
Scripts
[source]¶ Bases:
object
Utility class for loading scripts in a folder.
-
static
CheckScript
(text)[source]¶ Check if
text
is a valid script for PyUnity.Parameters: text (list) – List of lines Returns: If script is valid or not. Return type: bool Notes
This function checks each line to see if it matches at least one of these criteria:
- The line is an
import
statement - The line is just whitespace or blank
- The line is just a comment preceded by whitespace or nothing
- The line is a class definition
- The line has an indentation at the beginning
These checks are essential to ensure no malicious code is run to break the PyUnity engine.
- The line is an
-
static
LoadScripts
(path)[source]¶ Loads all scripts found in
path
.Parameters: path (Pathlike) – A path to a folder containing all the scripts Returns: A module that contains all the imported scripts Return type: ModuleType Notes
This function will add a module to
sys.modules
that is calledPyUnityScripts
, and can be imported like any other module. The module will also have a variable called__pyunity__
which shows that it is from PyUnity and not a real module. If an existing module namedPyUnityScripts
is present and does not have the__pyunity__
variable set, then a warning will be issued and it will be replaced.
-
static
pyunity.gui module¶
-
class
pyunity.gui.
Canvas
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.Component
A Component that manages GUI interactions and 2D rendering. Only GameObjects which are a descendant of a Canvas will be rendered.
-
class
pyunity.gui.
RectData
(min_or_both=None, max=None)[source]¶ Bases:
object
Class to represent a 2D rect.
Parameters:
-
class
pyunity.gui.
RectAnchors
(min_or_both=None, max=None)[source]¶ Bases:
pyunity.gui.RectData
A type of RectData which represents the anchor points of a RectTransform.
-
class
pyunity.gui.
RectOffset
(min_or_both=None, max=None)[source]¶ Bases:
pyunity.gui.RectData
Rect to represent the offset from the anchor points of a RectTransform.
-
static
Rectangle
(size, center=Vector2(0, 0))[source]¶ Create a rectangular RectOffset.
Parameters: Returns: The generated RectOffset
Return type:
-
static
-
class
pyunity.gui.
RectTransform
(transform)[source]¶ Bases:
pyunity.core.SingleComponent
A Component that represents the size, position and orientation of a 2D object.
-
anchors
¶ Anchor points of the RectTransform. Measured between Vector2(0, 0) and Vector2(1, 1)
Type: RectAnchors
-
offset
¶ Offset vectors representing the offset of opposite corners from the anchors. Measured in pixels
Type: RectOffset
-
pivot
¶ Point in which the object rotates around. Measured between Vector2(0, 0) and Vector2(1, 1)
Type: Vector2
-
parent
¶
-
-
class
pyunity.gui.
GuiComponent
(transform, is_dummy=False)[source]¶ Bases:
pyunity.core.Component
A Component that represents a clickable area.
-
class
pyunity.gui.
NoResponseGuiComponent
(transform, is_dummy=False)[source]¶ Bases:
pyunity.gui.GuiComponent
A Component that blocks all clicks that are behind it.
-
class
pyunity.gui.
Image2D
(transform)[source]¶ Bases:
pyunity.gui.NoResponseGuiComponent
A 2D image component, which is uninteractive.
-
class
pyunity.gui.
Button
(transform)[source]¶ Bases:
pyunity.gui.GuiComponent
A Component that calls a function when clicked.
-
callback
¶ Callback function
Type: FunctionType
-
state
= 1
-
mouseButton
= 1
-
-
class
pyunity.gui.
FontLoader
[source]¶ Bases:
pyunity.gui.UnixFontLoader
-
class
pyunity.gui.
Font
(name, size, imagefont)[source]¶ Bases:
object
Font object to represent font data.
-
_font
¶ Image font object. Do not use unless you know what you are doing.
Type: ImageFont.FreeTypeFont
-
-
class
pyunity.gui.
TextAlign
[source]¶ Bases:
enum.IntEnum
An enumeration.
-
Left
= 1¶
-
Center
= 2¶
-
Right
= 3¶
-
-
class
pyunity.gui.
Text
(transform)[source]¶ Bases:
pyunity.gui.NoResponseGuiComponent
Component to render text.
-
rect
¶ RectTransform of the GameObject. Can be None
Type: RectTransform
Notes
Modifying
font
,text
, orcolor
will callGenTexture()
.-
centeredX
= 1
-
centeredY
= 2
-
-
class
pyunity.gui.
CheckBox
(transform, is_dummy=False)[source]¶ Bases:
pyunity.gui.GuiComponent
A component that updates the Image2D of its GameObject when clicked.
-
class
pyunity.gui.
Gui
[source]¶ Bases:
object
Helper class to create GUI GameObjects. Do not instantiate.
-
classmethod
MakeButton
(name, scene, text='Button', font=None, color=None, texture=None)[source]¶ Create a Button GameObject and add all relevant GameObjects to the scene.
Parameters: - name (str) – Name of the GameObject
- scene (Scene) – Scene to add all generated GameObjects to
- text (str, optional) – Text content of the button, by default “Button”
- font (Font, optional) – Default font to use, if None then “Arial” is used
- color (Color, optional) – Fill color of the button text, by default black
- texture (Texture2D, optional) – Texture for the button background.
Returns: A tuple containing the
RectTransform
of button, theButton
component and theText
component.Return type: Notes
This will create 3 GameObjects in this hierarchy:
<specified button name> |- Button |- Text
The generated GameObject can be accessed from the
gameObject
property of the returned components. TheButton
GameObject will have two components,Button
andRectTransform
. TheButton
GameObject will have two components,Image2D
andRectTransform
.
-
classmethod
MakeCheckBox
(name, scene)[source]¶ Create a CheckBox GameObject and add the appropriate components needed.
Parameters: Returns: A tuple of the
RectTransform
as well as theCheckBox
component.Return type: Notes
The generated GameObject can be accessed from the
gameObject
property of the returned components. The GameObject will have 3 properties added: aRectTransform
, aCheckBox
and anImage2D
.
-
classmethod
pyunity.input module¶
-
class
pyunity.input.
KeyState
[source]¶ Bases:
enum.IntEnum
An enumeration.
-
UP
= 1¶
-
DOWN
= 2¶
-
PRESS
= 3¶
-
NONE
= 4¶
-
-
class
pyunity.input.
KeyCode
[source]¶ Bases:
enum.IntEnum
An enumeration.
-
A
= 1¶
-
B
= 2¶
-
C
= 3¶
-
D
= 4¶
-
E
= 5¶
-
F
= 6¶
-
G
= 7¶
-
H
= 8¶
-
I
= 9¶
-
J
= 10¶
-
K
= 11¶
-
L
= 12¶
-
M
= 13¶
-
N
= 14¶
-
O
= 15¶
-
P
= 16¶
-
Q
= 17¶
-
R
= 18¶
-
S
= 19¶
-
T
= 20¶
-
U
= 21¶
-
V
= 22¶
-
W
= 23¶
-
X
= 24¶
-
Y
= 25¶
-
Z
= 26¶
-
Space
= 27¶
-
Alpha0
= 28¶
-
Alpha1
= 29¶
-
Alpha2
= 30¶
-
Alpha3
= 31¶
-
Alpha4
= 32¶
-
Alpha5
= 33¶
-
Alpha6
= 34¶
-
Alpha7
= 35¶
-
Alpha8
= 36¶
-
Alpha9
= 37¶
-
F1
= 38¶
-
F2
= 39¶
-
F3
= 40¶
-
F4
= 41¶
-
F5
= 42¶
-
F6
= 43¶
-
F7
= 44¶
-
F8
= 45¶
-
F9
= 46¶
-
F10
= 47¶
-
F11
= 48¶
-
F12
= 49¶
-
Keypad0
= 50¶
-
Keypad1
= 51¶
-
Keypad2
= 52¶
-
Keypad3
= 53¶
-
Keypad4
= 54¶
-
Keypad5
= 55¶
-
Keypad6
= 56¶
-
Keypad7
= 57¶
-
Keypad8
= 58¶
-
Keypad9
= 59¶
-
Up
= 60¶
-
Down
= 61¶
-
Left
= 62¶
-
Right
= 63¶
-
-
class
pyunity.input.
MouseCode
[source]¶ Bases:
enum.IntEnum
An enumeration.
-
Left
= 1¶
-
Middle
= 2¶
-
Right
= 3¶
-
-
class
pyunity.input.
Input
[source]¶ Bases:
object
-
classmethod
GetKey
(keycode)[source]¶ Check if key is pressed at moment of function call
Parameters: keycode (KeyCode) – Key to query Returns: If the key is pressed Return type: boolean
-
classmethod
GetKeyUp
(keycode)[source]¶ Check if key was released this frame.
Parameters: keycode (KeyCode) – Key to query Returns: If the key was released Return type: boolean
-
classmethod
GetKeyDown
(keycode)[source]¶ Check if key was pressed down this frame.
Parameters: keycode (KeyCode) – Key to query Returns: If the key was pressed down Return type: boolean
-
classmethod
GetKeyState
(keycode, keystate)[source]¶ Check key state at moment of function call
Parameters: Returns: If the key state matches
Return type: boolean
-
classmethod
GetMouse
(mousecode)[source]¶ Check if mouse button is pressed at moment of function call
Parameters: mousecode (MouseCode) – Mouse button to query Returns: If the mouse button is pressed Return type: boolean
-
classmethod
GetMouseUp
(mousecode)[source]¶ Check if mouse button was released this frame.
Parameters: mousecode (MouseCode) – Mouse button to query Returns: If the mouse button was released Return type: boolean
-
classmethod
GetMouseDown
(mousecode)[source]¶ Check if mouse button was pressed down this frame.
Parameters: mousecode (MouseCode) – Mouse button to query Returns: If the mouse button was pressed down Return type: boolean
-
classmethod
GetMouseState
(mousecode, mousestate)[source]¶ Check for mouse button state at moment of function call
Parameters: Returns: If the mouse button state matches
Return type: boolean
-
classmethod
GetAxis
(axis)[source]¶ Get the value for the specified axis. This is always between -1 and 1.
Parameters: axis (str) – Specified axis Returns: Axis value Return type: float Raises: PyUnityException
– If the axis is not a valid axis
-
classmethod
pyunity.loader module¶
Utility functions related to loading and saving PyUnity meshes and scenes.
This will be imported as pyunity.Loader
.
-
pyunity.loader.
LoadObj
(filename)[source]¶ Loads a .obj file to a PyUnity mesh.
Parameters: filename (str) – Name of file Returns: A mesh of the object file Return type: Mesh
-
pyunity.loader.
LoadMesh
(filename)[source]¶ Loads a .mesh file generated by SaveMesh. It is optimized for faster loading.
Parameters: filename (str) – Name of file relative to the cwd Returns: Generated mesh Return type: Mesh
-
pyunity.loader.
SaveMesh
(mesh, name, filePath=None)[source]¶ Saves a mesh to a .mesh file for faster loading.
Parameters: - mesh (Mesh) – Mesh to save
- name (str) – Name of the mesh
- filePath (str, optional) – Pass in __file__ to save in directory of script, otherwise pass in the path of where you want to save the file. For example, if you want to save in C:Downloads, then give “C:Downloadsmesh.mesh”. If not specified, then the mesh is saved in the cwd.
-
pyunity.loader.
components
= {'AABBoxCollider': <class 'pyunity.physics.core.AABBoxCollider'>, 'AudioListener': <class 'pyunity.audio.AudioListener'>, 'AudioSource': <class 'pyunity.audio.AudioSource'>, 'Camera': <class 'pyunity.render.Camera'>, 'Light': <class 'pyunity.core.Light'>, 'MeshRenderer': <class 'pyunity.core.MeshRenderer'>, 'Rigidbody': <class 'pyunity.physics.core.Rigidbody'>, 'SphereCollider': <class 'pyunity.physics.core.SphereCollider'>, 'Transform': <class 'pyunity.core.Transform'>}¶ List of all components by name
pyunity.logger module¶
Utility functions to log output of PyUnity.
This will be imported as pyunity.Logger
.
-
class
pyunity.logger.
Level
(abbr, name)[source]¶ Bases:
object
Represents a level or severity to log. You should never instantiate this directly, instead use one of Logging.OUTPUT, Logging.INFO, Logging.DEBUG, Logging.ERROR or Logging.WARN.
-
class
pyunity.logger.
Special
(func)[source]¶ Bases:
object
Class to represent a special line to log. You should never instantiate this class, instead use one of Logger.RUNNING_TIME.
-
pyunity.logger.
LogLine
(level, *message, silent=False)[source]¶ Logs a line in latest.log found in these two locations: Windows:
%appdata%\PyUnity\Logs\latest.log
Other:/tmp/pyunity/logs/latest.log
Parameters: level (Level) – Level or severity of log.
-
pyunity.logger.
LogException
(e)[source]¶ Log an exception.
Parameters: e (Exception) – Exception to log
-
pyunity.logger.
LogSpecial
(level, type)[source]¶ Log a line of level level with a special line that is generated at runtime.
Parameters:
pyunity.meshes module¶
Module for meshes created at runtime.
-
class
pyunity.meshes.
Mesh
(verts, triangles, normals, texcoords=None)[source]¶ Bases:
object
Class to create a mesh for rendering with a MeshRenderer
Parameters: -
triangles
¶ List of lists containing triangles joining up the vertices. Each int is the index of a vertex above. The list is two-dimesional, meaning that each item in the list is a list of three ints.
Type: list
-
texcoords
¶ List of lists containing the texture coordinate of each vertex. The list is two-dimesional, meaning that each item in the list is a list of two floats.
Type: list (optional)
Notes
When any of the mesh attributes are updated while a scene is running, you must use
compile(force=True)
to update the mesh so that it is displayed correctly.>>> mesh = Mesh.cube(2) >>> mesh.vertices[1] = Vector3(2, 0, 0) >>> mesh.compile(force=True)
-
static
quad
(size)[source]¶ Creates a quadrilateral mesh.
Parameters: size (float) – Side length of quad Returns: A quad centered at Vector3(0, 0) with side length of size
facing in the direction of the negative z axis.Return type: Mesh
-
pyunity.render module¶
Classes to aid in rendering in a Scene.
-
pyunity.render.
gen_buffers
(mesh)[source]¶ Create buffers for a mesh.
Parameters: mesh (Mesh) – Mesh to create buffers for Returns: Tuple containing a vertex buffer object and an index buffer object. Return type: tuple
-
pyunity.render.
gen_array
()[source]¶ Generate a vertex array object.
Returns: A vertex buffer object of floats. Has 3 elements: # vertex # normal # texcoord x, y, z, a, b, c, u, v
Return type: Any
-
class
pyunity.render.
Shader
(vertex, frag, name)[source]¶ Bases:
object
-
compile
()[source]¶ Compiles shader and generates program. Checks for errors.
Notes
This function will not work if there is no active framebuffer.
-
static
fromFolder
(path, name)[source]¶ Create a Shader from a folder. It must contain
vertex.glsl
andfragment.glsl
.Parameters:
-
setVec3
(var, val)[source]¶ Set a
vec3
uniform variable.Parameters: - var (bytes) – Variable name
- val (Any) – Value of uniform variable
-
setMat4
(var, val)[source]¶ Set a
mat4
uniform variable.Parameters: - var (bytes) – Variable name
- val (Any) – Value of uniform variable
-
setInt
(var, val)[source]¶ Set an
int
uniform variable.Parameters: - var (bytes) – Variable name
- val (Any) – Value of uniform variable
-
-
class
pyunity.render.
Camera
(transform)[source]¶ Bases:
pyunity.core.SingleComponent
Component to hold data about the camera in a scene.
-
fov
¶ FOV of camera
-
orthoSize
¶
-
Render
(renderers, lights)[source]¶ Render specific renderers, taking into account light positions.
Parameters: - renderers (List[MeshRenderer]) – Which meshes to render
- lights (List[Light]) – Lights to load into shader
-