회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인PC가 아닐 경우 타인이 로그인할 수 있습니다.
PC를 여러사람이 사용하는 공공장소에서는 체크하지 마세요.
소셜네트워크 서비스를 통해서 로그인하시면 별도의 로그인 절차없이 회원서비스를 이용하실 수 있습니다.


최근 게시물

1.노션에서 작성 중

1.노션에서 작성 중

개편하기 전까지 노션에서 작성 중

2024.04.04//read more

2.ChatGPT

2.ChatGPT

OpenAI로 대규모 언어 모델대화형...

2023.03.16//read more

3.노코딩 게임 엔진 - 빌..

3.노코딩 게임 엔진 - 빌..

빌드 지원안드로이드iOS윈도우즈특이사...

2023.03.14//read more

4.(완료) 미접속 회원 정..

4.(완료) 미접속 회원 정..

[완료] 36명의 회원을 정리하였습니...

2023.02.16//read more

5.매뉴얼 플러스 - 전자제..



안정적인 DNS 서비스 DNSEver
DNS Powered by DNSEver.com


Class (클래스)

푸딩뱃살 | 2013.11.26 23:46 | 조회 2772
Class (클래스)

클래스의 기본 의미는 여기서 다루진 않겠다.
클래스 설명은 Inventory 한에서 작성되었다.

클래스는 스크립트를 생성할 때의 이름으로 자동으로 생성 되는 MonoBehaviour 클래스 기반으로 작성되어 진다.
파일명과 파일 안에 있는 MonoBehaviour의 클래스명과 같아야 하고, 스크립트명을 지을 때도 미리 신경을 써줘야 한다.

예제에서는 Inventory, MovementControls, Shooting 3개의 클래스를 분할 처리하는 것을 SingleCharacterScript 1개의 클래스로 변환하여 관리가 편리해지는 목적을 둔다. 다만 복잡하지 않게 충분히 클래스를 설계하여 작성하는 것을 권장한다.

*클래스 안의 서브 클래스
기본적으로 스크립트 파일을 생성할 때 클래스명이 생성되며 그 안에 클래스를 활용 할 수 있도록 서브 클래스가 존재한다.
서브 클래스 안엔 서브 클래스명과 같은 이름의 함수들이 존재해야 한다. 같은 이름의 함수들은 필요 시에 계속 생성 가능하고, 인스턴스 구분 또한 인자의 갯수로 적용된다.

그냥 작동해 보기
1. scene에 cube로 만든 바닥(floor)과 바닥위에 cube를 하나 생성한다.
2. 아래 bold된 이름으로 4개의 스크립트를 작성한다.
3. cube에 Inventory, MovementControls, Shooting 스크립트를 cube에 적용한다.
4. 실행하여 움직여 본다.
5. Inventory, MovementControls, Shooting 스크립트 끄고, SingleCharacterScript 적용하여 실행해 본다.

SingleCharacterScript
using UnityEngine;
using System.Collections;

public class SingleCharacterScript : MonoBehaviour
{
    public class Stuff
    {
        public int bullets;
        public int grenades;
        public int rockets;
        
        public Stuff(int bul, int gre, int roc)
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
    }
    
    
    public Stuff myStuff = new Stuff(10, 7, 25);
    public float speed;
    public float turnSpeed;
    public Rigidbody bulletPrefab;
    public Transform firePosition;
    public float bulletSpeed;
    
    
    void Update ()
    {
        Movement();
        Shoot();
    }
    
    
    void Movement ()
    {
        float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
        
        transform.Translate(Vector3.forward * forwardMovement);
        transform.Rotate(Vector3.up * turnMovement);
    }
    
    
    void Shoot ()
    {
        if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
        {
            Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
            bulletInstance.AddForce(firePosition.forward * bulletSpeed);
            myStuff.bullets--;
        }
    }
}

Inventory
using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour
{
    //서브 클래스
    public class Stuff
    {
        //변수값들 선언
        public int bullets;
        public int grenades;
        public int rockets;
        //추가된 변수
        public float fuel;
        
        //서브 클래스와 그 안의 함수들의 이름이 같아야 한다.
        public Stuff(int bul, int gre, int roc)
        {
            //인자로 들어온 값들을 치환
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
        
        //추가적인 변수를 수행할 때 따로 함수로 생성
        public Stuff(int bul, float fu)
        {
            //인자로 들어온 값들을 치환
            bullets = bul;
            fuel = fu;
        }
        
        // Constructor
        public Stuff ()
        {
           //변수 초기화
            bullets = 1;
            grenades = 1;
            rockets = 1;
        }
    }
    

    // Creating an Instance (an Object) of the Stuff class
    // 인스턴스 생성
    // public 서브클래스명 인스턴스명 = new 서브클래스안의 함수
    public Stuff myStuff = new Stuff(50, 5, 5);
    // Stuff(인자1,인자2) 함수의 인스턴스 생성
    public Stuff myOtherStuff = new Stuff(50, 1.5f);
    
    void Start()
    {
        Debug.Log(myStuff.bullets); 
    }
}

MovementControls
usng UnityEngine;
using System.Collections;

public class MovementControls : MonoBehaviour
{
    public float speed;
    public float turnSpeed;
    
    
    void Update ()
    {
        Movement();
    }
    
    
    void Movement ()
    {
        float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
        
        transform.Translate(Vector3.forward * forwardMovement);
        transform.Rotate(Vector3.up * turnMovement);
    }
}

Shooting
using UnityEngine;
using System.Collections;

public class Shooting : MonoBehaviour
{
    public Rigidbody bulletPrefab;
    public Transform firePosition;
    public float bulletSpeed;
    
    
    private Inventory inventory;
    
    
    void Awake ()
    {
        inventory = GetComponent();
    }
    
    
    void Update ()
    {
        Shoot();
    }
    
    
    void Shoot ()
    {
        if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
        {
            Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
            bulletInstance.AddForce(firePosition.forward * bulletSpeed);
            inventory.myStuff.bullets--;
        }
    }
}
참고
http://unity3d.com/learn/tutorials/modules/beginner/scripting/classes
146개(6/8페이지)
유니티
번호 제목 글쓴이 조회 날짜
공지 유니티 강좌 모음(영문) 푸딩뱃살 60389 2013.08.28 12:02
공지 유니티 경고, 에러 모음 (재정리 예정) 첨부파일 [1+1] 푸딩뱃살 71265 2013.08.12 00:09
44 [애셋] NGUI & PlayMaker - Random Button 첨부파일 푸딩뱃살 7394 2014.01.23 02:09
43 [애셋] PlayMaker - Random String 첨부파일 푸딩뱃살 5702 2014.01.22 03:29
42 [애셋] NGUI & PlayMaker - 웹툰 앱을 만들기 첨부파일 푸딩뱃살 7085 2014.01.20 00:25
41 [애셋] NGUI를 이용한 스크롤 사용하기 첨부파일 푸딩뱃살 9922 2014.01.15 03:21
40 [애셋] NGUI & PlayMaker를 이용한 텍스트 이동하기 첨부파일 푸딩뱃살 8264 2014.01.15 01:07
39 [애셋] NGUI 기본 첨부파일 푸딩뱃살 7948 2014.01.10 03:03
38 [애셋] PlayMaker 기본 첨부파일 푸딩뱃살 7731 2014.01.10 01:30
37 [유니티] Character Controller 캐릭터 컨트롤러 첨부파일 푸딩뱃살 8916 2013.12.23 23:52
36 [스트립트] raycast 예제 첨부파일 푸딩뱃살 2238 2013.12.11 13:40
35 [유니티] unityPackage 만들기 첨부파일 푸딩뱃살 12046 2013.11.29 14:35
34 [유니티] Mecanim으로 애니메이션 연결 첨부파일 푸딩뱃살 8153 2013.11.28 14:12
>> [스트립트] Class (클래스) 푸딩뱃살 2773 2013.11.26 23:46
32 [참고] Unity 디컴파일 - Unity 3D Obfuscator 사용법 첨부파일 푸딩뱃살 4918 2013.11.24 16:56
31 [참고] Unity 3D Obfuscator 첨부파일 푸딩뱃살 7987 2013.11.24 01:10
30 [스트립트] GUI.Button() 예제 첨부파일 푸딩뱃살 4951 2013.11.22 00:49
29 [스트립트] 마우스 제어 적용 (클릭,오버,아웃) 첨부파일 푸딩뱃살 5785 2013.11.21 14:29
28 [소셜] Unite 2013 - Connect Unity gamers across platforms with 푸딩뱃살 1516 2013.11.19 18:49
27 [소셜] Facebook SDK for Unity Tutorials (iOS, Android,Web) 푸딩뱃살 5154 2013.11.19 14:28
26 [참고] Unite Vancouver 2013 Keynote 푸딩뱃살 3158 2013.11.13 20:42
25 [정보] 유니티, 2D 개발 툴 장착한 ‘유니티 4.3’ 전 세계 동시 공개 첨부파일 푸딩뱃살 3939 2013.11.13 20:26