I use Unity 2017.1.0p5 and Visual Studio 2017 for this tutorial.
Here is what a new project looks like in Unity3D. Your screen probably looks different because Unity allows you to rearrange all windows. Find all window options under the Window menu item.
A cube has now been added to the scene and the inspector shows its properties. The window title shows an asterisk in the text to indicate our scene has not been saved yet. Saving the scene is optional for this tutorial but here is how it works:
main
and click SaveA rigid body enables game objects like our cube to be controlled by Unity’s physics engine. By default, Unity will control the objects gravity, resistance, etcetera. It also allows you as a developer to program your own scripts to control the object. And that’s why we will add the rigid body because it allows us to access to the game object with GetComponent<Rigidbody>()
in C#
0
(this turns the resistance off)To make the cube go spinning, we need to add a C# script to the cube.
Rotator
and click Create and AddA script has now been added and attached to the Cube
Rotator
to open in Visual StudioHere is how it looks like in Visual Studio:
Let’s cleanup the code a little bit.
// Use this for initialization
Your code should look like:
using UnityEngine; public class Rotator : MonoBehaviour { void Start() { } }
Do you remember that we added the Rigid Body to our cube? Here is where we are going to use it. Change your code to:
using UnityEngine; public class Rotator : MonoBehaviour { void Start() { var rb = GetComponent<Rigidbody>(); rb.angularVelocity = Random.insideUnitSphere; } }
Because we added the Rigid Body, we can now access it in C#. Once we have stored the Rigid Body in the variable rg, we can set its angularVelocity
, which is a Vector3 where X, Y and Z are the radians per second our cube needs to rotate. To create random values for X, Y and Z, we create a random vector using the Random class from Unity. Random.insideUnitSphere
returns a random point inside a sphere with Radius = 1.
We now have a rotating cube in Unity!