Skip to content

Instantly share code, notes, and snippets.

Last active May 4, 2019 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SenpaiRar/8fd1cf6a9fbc711ecf02f9a5c3e459c3 to your computer and use it in GitHub Desktop.
Save SenpaiRar/8fd1cf6a9fbc711ecf02f9a5c3e459c3 to your computer and use it in GitHub Desktop.
This is the code that handles Crates. Notice how it inherits from ClickableParent, giving it the ability to be clicked on.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crate : ClickableParent
public List<GameObject> ItemsInside = new List<GameObject>(); //A list is a collection of objects that can be accessed through a numbered list. In this case it holds our prefabs (Picture 1)
public int NumberOfItemsToSpawn; //This decides how many times we loop in OnClick(); IE it decides how many objects to spawn
public float MinimumDistance;
public AudioClip Clip;
public AudioSource Source;
void Start(){
Source = GameObject.Find("Player").GetComponent<AudioSource>();
public override void OnClick(Vector3 ClickPosition)
if(Vector3.Distance(ClickPosition, transform.position) <= MinimumDistance){
for (int i = 0; i < NumberOfItemsToSpawn; i++) //We loop through this NumberOfItemsToSpawn times
//We make a gameobject x equal to a copied version of a randomly selected prefab from the list (ItemsInside[Random.Range(0, ItemsInside.Count)])
//Instantiate is a built in Unity command that takes in a gameobject, vector3, and a rotation and copies that gameobject with that position and rotation
GameObject x = Instantiate(ItemsInside[Random.Range(0, ItemsInside.Count)], transform.position, Quaternion.identity) as GameObject;
//We then add an Explosiion force which we do with a built in function, giving it a satisyfying pop when the crate is clicked
x.GetComponent<Rigidbody>().AddExplosionForce(10, transform.position, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment