스크립트 파일의 사용과 객체 속성제어

1.스크립트 파일의 생성

script
유니티의 스크립트 파일은 [Assets] -> [Scripts] 폴더에서 오른쪽 마우스 메뉴 -> Create -> C# Script 메뉴를 통해 생성할 수 있습니다.
이 생성된 스크립트 파일을 게임화면내의 객체에 드래그하여 적용되도록 할 수 있습니다.

2.기본 스크립트 파일

생성된 스크립트의 기본 소스는 아래와 같습니다.

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

public class MainController : MonoBehaviour {

    // Start is called before the first frame update
    void Start() {

    }

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

    }
}

기본적으로 Start 메소드와 Update 메소드가 있습니다.
다양한 라이프사이클별 메소드가 있으며 아래 유니티 홈페이지에서 확인이 가능합니다.
https://docs.unity3d.com/kr/current/Manual/ExecutionOrder.html

변수 선언 및 확인

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

public class MainController : MonoBehaviour {

    public int timer = 0;

    // Start is called before the first frame update
    void Start() {
        Debug.Log("초기화가 이루어졌습니다.");
    }

    // Update is called once per frame
    void Update() {
        timer = timer + 1;
        Debug.Log(timer + "번째 업데이트");
    }
}

숫자형의 timer라는 변수를 생성하여 0으로 초기화 하였습니다.
Start 메소드를 통해 게임이 시작되면 초기화 안내문구가 로그에 남고,
Update 메소드를 통해 매 프레임마다 업데이트가 몇번째인지 로그가 남게됩니다.
위 로그는 유니티 화면내의 Console 탭에서 확인할 수 있습니다.

객체의 속성 제어

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

public class MainController : MonoBehaviour {

    public int timer = 0; 
    public GameObject capsule; //게임오브젝트를 선언
    public float speed = 3.0f; //움직일 스피드값 선언

    // Start is called before the first frame update
    void Start() {
        Debug.Log("초기화가 이루어졌습니다.");
                //capsule이라는 변수에 capsule 이라는 이름을 가진 게임객체 할당
        capsule = GameObject.Find("Capsule");
    }

    // Update is called once per frame
    void Update() {
        timer = timer + 1;
        Debug.Log(timer + "번째 업데이트");
        capsule.GetComponent<Transform>().Translate(Vector3.forward * speed * Time.deltaTime);
                //capsule 게임객체를 앞으로 이동
    }
}

유니티의 여러 메소드나 사용되었으나, 현재는 외우기보다는 작성방법 정도만 익히는것이 좋습니다.
Time.deltaTime은 어떤 컴퓨터에서든지 시간을 맞춰주기 위해 사용합니다.
작성후 게임을 실행해보면 객체가 앞으로 이동하는것을 확인할 수 있습니다.

this의 활용

위 소스처럼 Find 메소드를 통해 객체를 찾을수도 있지만 this를 활용할 수도 있습니다.
this는 스크립트가 주입된 객체를 참조합니다.

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

public class MainController : MonoBehaviour {

    public int timer = 0; 
    public GameObject capsule;
    public float speed = 3.0f;

    // Start is called before the first frame update
    void Start() {
        Debug.Log("초기화가 이루어졌습니다.");
    }

    // Update is called once per frame
    void Update() {
        timer = timer + 1;
        Debug.Log(timer + "번째 업데이트");
    // this의 활용
        this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}