0% found this document useful (0 votes)
39 views4 pages

Scripts As Behaviour Components

This document contains code snippets demonstrating various programming concepts in Unity such as scripts, variables, functions, if/else statements, for loops, while loops, do/while loops, foreach loops, scope, access modifiers, and the Update and FixedUpdate methods. The snippets show how to get component references, change material colors, log values, increment/decrement counters, and perform conditional checks and loops to iterate through arrays and repeat actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views4 pages

Scripts As Behaviour Components

This document contains code snippets demonstrating various programming concepts in Unity such as scripts, variables, functions, if/else statements, for loops, while loops, do/while loops, foreach loops, scope, access modifiers, and the Update and FixedUpdate methods. The snippets show how to get component references, change material colors, log values, increment/decrement counters, and perform conditional checks and loops to iterate through arrays and repeat actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Scripts as Behaviour Components void Start ()


{
//this line is there to tell me the x position of my object

using UnityEngine; /*Hi there!


using System.Collections; * this is two lines!
* */
public class ExampleBehaviourScript : MonoBehaviour Debug.Log(transform.position.x);
{
void Update() if(transform.position.y <= 5f)
{ {
if (Input.GetKeyDown(KeyCode.R)) Debug.Log ("I'm about to hit the ground!");
{ }
GetComponent<Renderer> ().material.color = Color.red; }
} }
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green; 4. IF Statements
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue; using UnityEngine;
} using System.Collections;
}
} public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
2. Variables and Functions float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
using UnityEngine;
using System.Collections;
void Update ()
public class VariablesAndFunctions : MonoBehaviour
{
{
if(Input.GetKeyDown(KeyCode.Space))
int myInt = 5;
TemperatureTest();

coffeeTemperature -= Time.deltaTime * 5f;


void Start ()
}
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
void TemperatureTest ()
}
{
// If the coffee's temperature is greater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
int MultiplyByTwo (int number)
{
{
// ... do this.
int result;
print("Coffee is too hot.");
result = number * 2;
}
return result;
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
}
else if(coffeeTemperature < coldLimitTemperature)
}
{
3. Conventions and Syntax // ... do this.
print("Coffee is too cold.");
using UnityEngine; }
using System.Collections; // If it is neither of those then...
else
public class BasicSyntax : MonoBehaviour {
{ // ... do this.

print("Coffee is just right."); {


} print ("Hello World");
}
} }while(shouldContinue == true);
}
}
5. ForLoop
using UnityEngine;
8. ForeachLoop
using System.Collections; using UnityEngine;
using System.Collections;
public class ForLoop : MonoBehaviour
{ public class ForeachLoop : MonoBehaviour
int numEnemies = 3; {
void Start ()
{
void Start () string[] strings = new string[3];
{
for(int i = 0; i < numEnemies; i++) strings[0] = "First string";
{ strings[1] = "Second string";
Debug.Log("Creating enemy number: " + i); strings[2] = "Third string";
}
} foreach(string item in strings)
} {
print (item);
6. WhileLoop }
}
using UnityEngine; }
using System.Collections;

public class WhileLoop : MonoBehaviour 9. ScopeAndAccessModifiers


{
int cupsInTheSink = 4; using UnityEngine;
using System.Collections;

void Start () public class ScopeAndAccessModifiers : MonoBehaviour


{ {
while(cupsInTheSink > 0) public int alpha = 5;
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--; private int beta = 0;
} private int gamma = 5;
}
}
private AnotherClass myOtherClass;
7. DoWhileLoop
using UnityEngine; void Start ()
using System.Collections; {
alpha = 29;
public class DoWhileLoop : MonoBehaviour
{ myOtherClass = new AnotherClass();
void Start() myOtherClass.FruitMachine(alpha, myOtherClass.apples);
{ }
bool shouldContinue = false;

do void Example (int pens, int crayons)


{
int answer; void Start ()
answer = pens * crayons * alpha; {
Debug.Log(answer); Debug.Log("Start called.");
} }
}

void Update ()
{ 12. 12. Update and FixedUpdate
Debug.Log("Alpha is set to: " + alpha);
}
}

10. AnotherClass using UnityEngine;


using System.Collections;
using UnityEngine;
using System.Collections; public class UpdateAndFixedUpdate : MonoBehaviour
{
public class AnotherClass void FixedUpdate ()
{ {
public int apples; Debug.Log("FixedUpdate time :" + Time.deltaTime);
public int bananas; }

private int stapler; void Update ()


private int sellotape; {
Debug.Log("Update time :" + Time.deltaTime);
}
public void FruitMachine (int a, int b) }
{
int answer;
answer = a + b;
Debug.Log("Fruit total: " + answer); 13. Enabling and Disabling Components
}

using UnityEngine;
private void OfficeSort (int a, int b) using System.Collections;
{
int answer; public class EnableComponents : MonoBehaviour
answer = a + b; {
Debug.Log("Office Supplies total: " + answer); private Light myLight;
}
}
void Start ()
{
11. 11. Awake and Start myLight = GetComponent<Light>();
}
using UnityEngine;
using System.Collections; void Update ()
{
public class AwakeAndStart : MonoBehaviour if(Input.GetKeyUp(KeyCode.Space))
{ {
void Awake () myLight.enabled = !myLight.enabled;
{ }
Debug.Log("Awake called."); }
} }

14. ActiveObjects 17. CameraLookAt


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

public class ActiveObjects : MonoBehaviour public class CameraLookAt : MonoBehaviour


{ {
void Start () public Transform target;
{
gameObject.SetActive(false); void Update ()
} {
} transform.LookAt(target);
15. CheckState }
}

using UnityEngine;
using System.Collections;

public class CheckState : MonoBehaviour 18. KeyInput


{
public GameObject myObject; using UnityEngine;
using System.Collections;
using UnityEngine.UI;
void Start ()
{ public class KeyInput : MonoBehaviour
Debug.Log("Active Self: " + myObject.activeSelf); {
Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy); public Image graphic;
} public Sprite standard;
} public Sprite downgfx;
public Sprite upgfx;
public Sprite heldgfx;
16. TransformFunctions public Text boolDisplay1;
public Text boolDisplay2;
using UnityEngine;
public Text boolDisplay3;
using System.Collections;
void Start()
public class TransformFunctions : MonoBehaviour
{
{
graphic.sprite = standard;
public float moveSpeed = 10f;
}
public float turnSpeed = 50f;
void Update()
{
void Update ()
bool down = Input.GetKeyDown(KeyCode.Space);
{
bool held = Input.GetKey(KeyCode.Space);
if(Input.GetKey(KeyCode.UpArrow))
bool up = Input.GetKeyUp(KeyCode.Space);
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
if(down)
if(Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
graphic.sprite = downgfx;
}
if(Input.GetKey(KeyCode.LeftArrow))
else if (held)
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
{
graphic.sprite = heldgfx;
if(Input.GetKey(KeyCode.RightArrow))
}
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
else if (up)
}
{
}
graphic.sprite = upgfx;
}
else
{ boolDisplay3.text = " " + held;
graphic.sprite = standard; }
} }

boolDisplay1.text = " " + down;


boolDisplay2.text = " " + held;
20. MouseClick
boolDisplay3.text = " " + held; using UnityEngine;
} using System.Collections;
}
public class MouseClick : MonoBehaviour
19. ButtonInput {

using UnityEngine; private Rigidbody rb;


using System.Collections;
using UnityEngine.UI; private void Awake()
{
public class ButtonInput : MonoBehaviour rb = GetComponent<Rigidbody>();
{ }
public Image graphic;
public Sprite standard; void OnMouseDown ()
public Sprite downgfx; {
public Sprite upgfx; rb.AddForce(-transform.forward * 500f);
public Sprite heldgfx; rb.useGravity = true;
public Text boolDisplay1; }
public Text boolDisplay2; }
public Text boolDisplay3;

void Start()
21. Singleton – scene manager
{ using UnityEngine;
graphic.sprite = standard; using UnityEngine.SceneManagement;
} using UnityEngine.UI;

void Update()
{ public class SceneManagerScript : MonoBehaviour
bool down = Input.GetButtonDown("Jump"); {
bool held = Input.GetButton("Jump"); public Text ValueTxt;
bool up = Input.GetButtonUp("Jump"); private void Start()
{
if(down) ValueTxt.text = PersistentManagerScript.Instance.Value.ToString();
{ }
graphic.sprite = downgfx; public void GoToFirstScene()
} {
else if (held) SceneManager.LoadScene("first");
{ PersistentManagerScript.Instance.Value++;
graphic.sprite = heldgfx; }
} public void GoToSecondScene()
else if (up) {
{ SceneManager.LoadScene("second");
graphic.sprite = upgfx; PersistentManagerScript.Instance.Value++;
}
else }
{
graphic.sprite = standard; }
}

boolDisplay1.text = " " + down;


boolDisplay2.text = " " + held;

22. Singleton – Persistent manager }


void B3Click(){
using System.Collections; Debug.Log ("Green Color");
using System.Collections.Generic; sprite = GetComponent<SpriteRenderer>();
using UnityEngine; sprite.color = Color.green;
}
public class PersistentManagerScript : MonoBehaviour // Update is called once per frame
{ void Update()
public static PersistentManagerScript Instance { get; private set; } {
}
public int Value; }

private void Awake()


{ 24. SceneTransition
if (Instance == null)
{ using UnityEngine;
Instance = this; using UnityEngine.SceneManagement;
DontDestroyOnLoad(gameObject); using UnityEngine.UI;
} public class SceneTransition : MonoBehaviour
else {
{ public InputField nameInputField;
Destroy(gameObject); public void StartGame()
} {
} string playerName = nameInputField.text;
} if (!string.IsNullOrEmpty(playerName))
{
// Store the player name for use in the next scene (you can use
23. Button UI PlayerPrefs or other methods).
PlayerPrefs.SetString("PlayerName", playerName);
// Load the next scene.
using System.Collections; SceneManager.LoadScene("WelcomeScene");
using System.Collections.Generic; }
using UnityEngine; }
using UnityEngine.UI; }
public class SetColor : MonoBehaviour
{ 25. Script "WelcomeMessage"
SpriteRenderer sprite;
public Color newColor; using UnityEngine;
public Button B1,B2,B3; using UnityEngine.UI;
// Start is called before the first frame update public class WelcomeMessage : MonoBehaviour
void Start() {
{ public Text welcomeText;
Button btn1 = B1.GetComponent<Button>(); void Start()
btn1.onClick.AddListener(B1Click); {
Button btn2 = B2.GetComponent<Button>(); string playerName = PlayerPrefs.GetString("PlayerName", "Player");
btn2.onClick.AddListener(B2Click); welcomeText.text = "Welcome, " + playerName + "!";
Button btn3 = B3.GetComponent<Button>(); }
btn3.onClick.AddListener(B3Click); }
}
void B1Click(){
Debug.Log ("Blue Color"); 26. BallMovement Script
sprite = GetComponent<SpriteRenderer>();
sprite.color = Color.blue; using UnityEngine;
} public class BallMovement : MonoBehaviour
void B2Click(){ {
Debug.Log ("Red Color"); public float speed = 5.0f;
sprite = GetComponent<SpriteRenderer>(); void Update()
sprite.color = Color.red; {
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalInput, verticalInput, 0) * speed
* Time.deltaTime;
transform.Translate(movement);
}
}

27. BallSizeControl

using UnityEngine;
using UnityEngine.UI;
public class BallSizeControl : MonoBehaviour
{
public Slider sizeSlider;
public float minSize = 1.0f;
public float maxSize = 5.0f;
private void Start()
{
sizeSlider.onValueChanged.AddListener(ChangeBallSize);
}
private void ChangeBallSize(float value)
{
float newSize = Mathf.Lerp(minSize, maxSize, value);
transform.localScale = new Vector3(newSize, newSize, newSize);
}
}
27. Scroll Texture Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SrollTex: monoBehaviour
{
public float ScrollX = 0.5f;
public float ScrollY = 0.5f;
void update()
{
float offsetX = Time.time * __________;
float offsetY = Time.time * __________;
GetComponent<Renderer>().material.mainTextureOffset = new Vector2(___________,
_________________);
}
}

You might also like