Basic Unity Scripts


using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController : MonoBehaviour {
public GameObject[] prefabs;

public float speed;
public Vector3 jump;
public Text countText;
public Text winText;

private Rigidbody rb;
private int count;

void Start ()
{
rb = GetComponent();
jump = new Vector3(0.0f, 2.0f, 0.0f);
count = 0;
SetCountText ();
winText.text = "";
}

void Update() {
if (Input.GetButtonDown("Jump")) {
print("space key was pressed");
rb.AddForce(jump * 2.0f, ForceMode.Impulse);
}
}

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

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

rb.AddForce (movement * speed);
}

void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ( "Pick Up"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}

void SetCountText ()
{
countText.text = "Count: " + count.ToString ();
if (count >= 12)
{
winText.text = "You Win!";
}
}

}


using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

public GameObject player;

private Vector3 offset;

void Start ()
{
offset = transform.position - player.transform.position;
}

void LateUpdate ()
{
transform.position = player.transform.position + offset;
}
}


using UnityEngine;
using System.Collections;

public class GroundSpawner : MonoBehaviour {

public GameObject[] prefabs;
public float spawnDistance;
private GameObject playerLastPosition;
private GameObject playerPosition;
float distanceTravelled = 0;
Vector3 lastPosition;

// Use this for initialization
void Start () {

// infinite coin spawning function, asynchronous
//StartCoroutine(SpawnGround());
playerPosition = GameObject.Find("Player");
lastPosition = playerPosition.transform.position;
}

// Update is called once per frame
void Update () {
distanceTravelled += Vector3.Distance(playerPosition.transform.position, lastPosition);
lastPosition = playerPosition.transform.position;
// Debug.Log("distanceTravelled is " + distanceTravelled);

}

}

on a prefab

using UnityEngine;
using System.Collections;

public class PickupSpawner : MonoBehaviour {

public GameObject[] prefabs;

// Use this for initialization
void Start () {

// infinite coin spawning function, asynchronous
StartCoroutine(SpawnGems());
}

// Update is called once per frame
void Update () {

}

IEnumerator SpawnGems() {
while (true) {

// number of coins we could spawn vertically
int gemsThisRow = Random.Range(1, 4);

// instantiate all coins in this row separated by some random amount of space
for (int i = 0; i Instantiate(prefabs[Random.Range(0, prefabs.Length)], new Vector3(26, Random.Range(-10, 10), 10), Quaternion.identity);
}

// pause 1-20 seconds until the next coin spawns
yield return new WaitForSeconds(Random.Range(1, 20));
}
}
}