Variables
using UnityEngine;
public class VariableExample : MonoBehaviour
{
public int playerScore = 0;
public float speed = 5.5f;
public string playerName = "Hero";
public bool isGameOver = false;
void Start()
{
Debug.Log("Player Name: " + playerName);
Debug.Log("Player Score: " + playerScore);
Debug.Log("Speed: " + speed);
Debug.Log("Is Game Over?: " + isGameOver);
}
}
Conditional
using UnityEngine;
public class ConditionExample : MonoBehaviour
{
public int health = 100;
void Update()
{
health -= 1;
Debug.Log("Health: " + health);
if (health <= 0)
{
Debug.Log("Game Over!");
}
}
}
Loop
for loop
using UnityEngine;
public class LoopExample : MonoBehaviour
{
void Start()
{
for (int i = 1; i <= 10; i++)
{
Debug.Log("Count: " + i);
}
int counter = 0;
while (counter < 5)
{
Debug.Log("While Count: " + counter);
counter++;
}
}
}
Function
using UnityEngine;
public class FunctionExample : MonoBehaviour
{
void Start()
{
SayHello();
int total = AddNumbers(3, 5);
Debug.Log("Total: " + total);
}
void SayHello()
{
Debug.Log("Hello, Unity!");
}
int AddNumbers(int a, int b)
{
return a + b;
}
}
Class
using UnityEngine;
public class ClassExample : MonoBehaviour
{
public class Player
{
public string name;
public int score;
public Player(string playerName, int playerScore)
{
name = playerName;
score = playerScore;
}
public void ShowInfo()
{
Debug.Log($"Player: {name}, Score: {score}");
}
}
void Start()
{
Player player1 = new Player("Hero", 10);
player1.ShowInfo();
}
}
Mono Behavior
using UnityEngine;
public class MonoBehaviorExample : MonoBehaviour
{
void Start()
{
Debug.Log("Start: Runs when game starts.");
}
void Update()
{
Debug.Log("Update: Runs during every frame.");
}
void FixedUpdate()
{
Debug.Log("FixedUpdate: Runs with specific frame.");
}
}