Eggys Games

News Archive

Unity - Basic Collisions in C#

In Unity the first thing you're gonna want to be using is collisions. This is what happens when 2 objects collide with each other, or rather two rigidbodies with colliders. Below is all you will need to get started. By adding a rigidbody and a box collider our object can now hit other objects in the scene.

Below I've included the functions that Unity uses to test for collision between objects. Simple copy and paste and then write inside the code you want to execute when these objects collide.

You will see their is triggers and normal. The difference with trigger is that the object will not collide with it in physics space, however it will still execute a hit-test. You use triggers on objects in the background like levers, scenery, doors etc. Where as normal collisions are for enemies and the player. 

These are the two components you need on an object to run a hit-test

Use This code below when you want a hit test between two objects

 //Basic Collision 
 void OnCollisionEnter2D (Collision2D col) {
    if (col.gameObject.tag == "NameOfObject") {
         ///Run Code 
     }
 }

 //Collision Exits
 void OnCollisionExit2D (Collision2D col) {
    if (col.gameObject.tag == "NameOfObject") {
         ///Run Code 
     }
 }

 //Non-Physics Collision
 void OnTriggerEnter2D (Collider2D col) {
 }

 //Non-Physics Collision Exit
 void OnTriggerExit2D (Collider2D col) {
 }


Leave a comment Posted in Game Making Programming by Eggy on

Unity - Spawning Objects Class in C#

Here is a nice simple class you can use if you want to spawn objects from another object in Unity. It allows you to simply drag and drop the class on an object and then in the inspector set the frequency of spawn, how fast to spawn and what to spawn.

It's quite simple yet very versatile to use in many projects. The timer keeps adding, when it goes over a certain amount you set known as the frequency then it will instantiate the object at its transform position and set the timer back to 0. Simple yet effective.

public class Spawn : MonoBehaviour {


    public Rigidbody2D ObjectToSpawn; 
    public Transform WhereToSpawn; 
    public int frequency; 
    public Vector3 random;

    private int spawntime = 0;

    void Update () {


        random = new Vector3 (Random.Range(0,5), 0, 0);

        spawntime++; 

        if (spawntime > frequency) {
            Instantiate (ObjectToSpawn, WhereToSpawn.position+random, WhereToSpawn.rotation);
            spawntime = 0; 
        }
        
    }

Putting our spawn code to good use by spawning zombies out a door



Leave a comment Posted in Game Making Programming by Eggy on