본문 바로가기
IT

[Unity/Zepeto] 싱글톤 만들기

by 배애앰이 좋아 2023. 7. 14.
반응형

 

프로젝트를 구현하다보면 scene 에 하나밖에 존재하지 않지만 여기저기 많이 쓰이는 class 들이 있습니다. 해당 class의 변수나 함수를 이용하기 위해서는 보통 Gameobject.Find 하거나 태그를 찾거나 직접 public 로 넣거나 하는데 이런 방법들은 종종 제대로 못 읽어서 오류가 나거나 비효율적이라고 합니다. 

 

보통 게임에서 위와 같은 class 들을 싱글톤으로 만들어서 처리해준다고 합니다. 

 

1. 싱글톤 만드는 방법

 

export default class AttachObject extends ZepetoScriptBehaviour {

    private static Instance : AttachObject;

    public static GetInstance() : AttachObject{
        if(!AttachObject.Instance){
            const targetObj = UnityEngine.GameObject.Find("AttachController");
            if(targetObj){
                AttachObject.Instance = targetObj.GetComponent<AttachObject>();
            }
        }
        return AttachObject.Instance;
    }
    
    public AttachGun(){ 
    }
}

 

위와 같은 함수 생성해주기

 

2. 다른 스크립트에서 싱글톤 사용하는 방법

 

import AttachObject from './AttachObject'; // 위에 선언

// AttachGun() 는 AttachObject 스크립트에 있는 public 함수
AttachObject.GetInstance().AttachGun(); // 다른 함수에 들어가서 사용

 

위 경우 따로 오브젝트 밑에 있는 스크립트를 찾을 필요없이 AttachObject.GetInstance() 로 Scene에 존재하는 해당 스크립트를 불려올 수 있습니다.

 

3. 위 코드의 활용 예제 코드

 

import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { ZepetoCharacter, ZepetoPlayers } from 'ZEPETO.Character.Controller';
import { Transform, Animator, GameObject, HumanBodyBones, Object } from 'UnityEngine';
import * as UnityEngine from 'UnityEngine'

export default class AttachObject extends ZepetoScriptBehaviour {

    private static Instance : AttachObject;

    // The object prefab to be attached on the body.
    public Gun1: GameObject;
    // The bone to attach the object to.
    public bodyBone: HumanBodyBones;

    private _localCharacter: ZepetoCharacter;

    public static GetInstance() : AttachObject{
        if(!AttachObject.Instance){
            const targetObj = UnityEngine.GameObject.Find("AttachController");
            if(targetObj){
                AttachObject.Instance = targetObj.GetComponent<AttachObject>();
            }
        }
        return AttachObject.Instance;
    }

    Start() {
        ZepetoPlayers.instance.OnAddedLocalPlayer.AddListener(() => {
            // Find the local player and set it to _localCharacter.
            this._localCharacter = ZepetoPlayers.instance.LocalPlayer.zepetoPlayer.character;
        });
    }

    AttachGun(){
        // Get the _localCharacter's animator component.
        const animator: Animator = this._localCharacter.ZepetoAnimator;
        // Get the position of the bone to attach the object to.
        const bone: Transform = animator.GetBoneTransform(this.bodyBone);
        // Create the object prefab.
        Object.Instantiate(this.Gun1, bone) as GameObject;
    }
}

 

좀 더 이론적인 활용 예시를 들어보자면, FPS 게임에서 총과 총알을 사용할 때, 총알 스크립트랑 총알을 관리해주는 스크립트를 따로 만들어서 총알 관리해주는 스크립트를 싱글톤으로 만들어줍니다. 그리고 총알 스크립트나 총알 오브젝트의 접근이 필요한 스크립트에 사용해주면 간편하게 해줄 수 있습니다.

 

경험상 게임 개발을 잘하기 위해서는 싱글톤 사용에 능숙해질 필요성이 있는 것 같습니다.

대부분 실무에서 많이 사용되기 때문입니다.

 

반응형

댓글