Useful functions in Unity

Andy Flatiron
4 min readDec 24, 2020

I’ve been working with Unity now, pushing to learn the language of C# and the program itself and it’s been quite the journey this past week. Most of the material I’ve been learning is from the Unity Learn website, but also from the “Unity Game Development Cookbook” by O’Reilly Publishing.

Here are some useful tips and functions that I will continue to reference as they will really help me out as I work on my personal project, hopefully they will help you too.

Spawning New Obstacles Every Few Seconds. Here we need to use the “Invoke Repeating” Method and call it on start, with this method we pass it, the function to call, the amount of time before spawning, and the set interval.

Here’s an example of how to use invoke repeating ( note these aren’t working examples they are coming out of my notebook, so some of the syntax and capitalization may be wrong, but nothing visual studio can’t fix!

public GameObject obstaclePrefabvoid start(){
invokeRepeating("SpawnObstacles", 1, 2)
}void SpawnObstacles(){
Instantiate(obstaclePrefab, new Vector3(x, y, z), obstaclePrefab.transform.rotation)
}

This will instantiate a new instance of the obstacle prefab game object that we passed into this SpawnController

Another useful function to now is how to know which object that your current object has collided with is to use the compare tag and set it to the name of the object. So for example if you are trying to keep track of when your player comes into contact with your enemy. In your inspector add a tag to your object, and then use the following method.

OnCollisionEnter(Collision collision){
if(collision.gameObject.CompareTag("Enemy"){
Debug.Log("Player has collided with Enemy")
}
}

What if we wanted to make our player object move horizontally how would we do that? Easy we first need to set a certain speed that we want it to move, then we just need to get the Axis from the built in Axis Finder. Then we can just transform the movement and multiply it by our horizontal input as follows

public Speed = 10f;//using public here so we can adjust in the inspector and find the perfect number! 
public float HorizontalInput;
void update(){
horizontalInput = Input.GetAxis("Horizontal")(1)
transform.Translate(Vector3.left)(2) * Time.DeltaTime * speed)3
}
  1. We are getting the coordinates from the user on horizontal axis — pulling from the left or right keys
  2. .left on the Vector3 automatically sets the position and movement of the object
  3. Multiply the vector with time and speed and you have an object that moves naturally in the environment

Now your update method is programmed to keep on watching from any input on either the left or right arrow keys. If there is movement, Vector3.left, will multiply with the integer that horizontal input is providing it. Very useful method for the future!

To this point how can we add jumps with physics! ? It’s also important here to make sure that we don’t Double Jump! Let’s set some variables such as our jump force (to make our jump more realistic), a gravity modifier that we’ll make public so we can use at any time and our rigid body of our player, which holds our gravity settings!

public float jumpForce;
public float gravityModifier;
public RigidBody playerRb;
1
  1. We are setting our variables all public so that we can reference them in the inspector and adjust our settings in the future — and RigidBody needs to be public so we can access it outside of this class
void start(){
playerRb = GetComponent<RigidBody>();
Physics.gravity *= gravityModifier
}

In the start method we are selecting the Rigidbody and setting it to the player variable — afterward we are multiplying and setting the gravity of the object to the gravityModifier, which we can edit it in the inspector.

void update(){if input.getKeyDown(keyCode.Space 1){ playerRb.AddForce(Vector3.up * JumpForce, forceMode.Impulse 2)
}
  1. KeyCode you can set any of the keys and they trigger upon touch, if you hold it doesn’t repeat like Get Axis
  2. forceMode.Impulse puts all the force on the object at once so it’s not spread out over time, you can see a direct impact of the space bar.

One more thing you can do is add a boolean and say that onGround is false once you press the space bar, this way you can’t double jump.

Let’s set up an on trigger event. So to set an on trigger, first you need to make sure that your ‘on trigger’ is selected on the mesh collidor and we need to apply tags similar to the onCollision.

private void onTriggerEnter(collider other){  if(other.compare_tag("powerup"){
hasPowerUp = true
}
}

In this function when an object is collided with another object that has a trigger it will change the hasPowerUp Variable to true. This is helpful to use, with another object that has a trigger vs. onCollisionEnter which is used for more physics based interactions.

Lastly, let’s set up a coroutine, used as a counter, which doesn’t require the use of the update function!

IEnumerator PowerUpCountdown(){
yield return WaitForSeconds(2)
hasPowerUp = false
}

here we are using the IEnumerator and Yield statements to allow us to use the WaitForSeconds() method which is built in to Unity. When the Coroutine is called, wait for seconds, will wait 2 seconds before applying the rest of the method. We can call the coroutine in the start() method

public bool hasPowerUp = true; //public to test in the inspectorprivate void onTriggerEnter(collider other){   if(other.compareTag("PowerUp"){
hasPowerUp = true
startCoroutine(powerUpCountdown())

}
}

When we collide with the powerUp object, it is automatically set to true and then we start the coroutine, when the coroutine is finished, it sets the boolean to false, so that the powerUp is no longer active!

Those are just some helpful functions to get started, hopefully they will help you along your coding journey!

--

--