Unity Basics

JunDev·2025년 3월 10일

Unity

목록 보기
2/8

Variables

using UnityEngine;
public class VariableExample : MonoBehaviour
{
	// variable declare
	public int playerScore = 0;
	public float speed = 5.5f;
	public string playerName = "Hero";
	public bool isGameOver = false;
 
void Start()
{
	// variable output
	Debug.Log("Player Name: " + playerName);
	Debug.Log("Player Score: " + playerScore);
	Debug.Log("Speed: " + speed);
	Debug.Log("Is Game Over?: " + isGameOver);
	}
}

// Output:
// Player Name: Hero
// Player Score: 0
// Speed: 5.5
// Is Game Over?: False

Conditional

using UnityEngine;

public class ConditionExample : MonoBehaviour
{
	public int health = 100;

	void Update()
	{
		health -= 1; // decrease by 1
		Debug.Log("Health: " + health);
 	
    	// conditional
 		if (health <= 0)
 		{
 			Debug.Log("Game Over!");
 		}
	}
}

Loop

for loop

using UnityEngine;

public class LoopExample : MonoBehaviour
{
	void Start()
 	{
 		// for: output from 1 to 10
 		for (int i = 1; i <= 10; i++)
 		{
 			Debug.Log("Count: " + i);
 		}
 		
        // while: run only when the condition is true
 		int counter = 0;
 		while (counter < 5)
 		{
 			Debug.Log("While Count: " + counter);
 			counter++;
 		}
 	}
}

Function

using UnityEngine;

public class FunctionExample : MonoBehaviour
{
	void Start()
 	{
 		SayHello(); // function call
 		int total = AddNumbers(3, 5);
 		Debug.Log("Total: " + total); // Total: 8
 	}

 	// set function
 	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();
    }
}

// Output:
// Player: Hero, Score, 10

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.");
    }
}
profile
Jun's Dev Journey

0개의 댓글