Skip to content

Instantly share code, notes, and snippets.

@neogeek
Last active April 17, 2017 08:01
Show Gist options
  • Save neogeek/83109982cfb865aaff3d to your computer and use it in GitHub Desktop.
Save neogeek/83109982cfb865aaff3d to your computer and use it in GitHub Desktop.
A collection of useful Unity snippets (CSharp).

#Unity Snippets

A collection of useful Unity snippets (CSharp).

##Movement

Boundary.cs

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary {
	
	public float xMin, xMax, yMin, yMax;
	
}

###Basic X/Y Movement

PlayerController.cs

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public float speed;
	public Boundary boundary;
	
	void FixedUpdate () {
		
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

		rigidbody.velocity = movement * speed;

		rigidbody.position = new Vector2 (
			Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
			Mathf.Clamp (rigidbody.position.y, boundary.yMin, boundary.yMax)
		);
	
	}
	
}

##Spawn

###Basic Enemy Spawn

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
	
	public GameObject enemy;
	public int enemyCount;
	public Boundary boundary;
	public float spawnWait;
	public float startWait;
	public float waveWait;
	
	void Start () {

		StartCoroutine (SpawnEnemies ());
	
	}

	IEnumerator SpawnEnemies () {

		yield return new WaitForSeconds (startWait);
		
		while (true) {
			
			for (int i = 0; i < enemyCount; i++) {
				
				Vector3 spawnPosition = new Vector3 (
					Random.Range (boundary.xMin, boundary.xMax),
					Random.Range (boundary.yMin, boundary.yMax),
					0.0f
				);
				Quaternion spawnRotation = Quaternion.identity;

				Instantiate (enemy, spawnPosition, spawnRotation);

				yield return new WaitForSeconds (spawnWait);

			}

			yield return new WaitForSeconds (waveWait);

		}

	}

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment