유니티

상속을 이용해 다른 이름의 클래스 스크립트 접근하기

tose33 2021. 7. 4. 11:49

프로젝트 진행중에 문제가 생겼다.

구조가 메인타이틀 화면이 있고 거기서 여러개의 작은 미니게임을 선택해서 플레이 하는 방식인데,

각각의 미니게임마다 각각의 게임의 점수를 관리하는 스크립트가 있다.

그런데 이제 하나의 스크립트로 이 각각의 서로다른 스크립트를 상황에 따라 접근하고 싶은데 모두 이름이 다르기 때문에 어떤 방식으로 접근해야 할지 찾아보다가 상속을 이용했다.

 

먼저 부모가 될 parent.cs 클래스를 만든다.

using UnityEngine;

public class parent : MonoBehaviour
{
    // 
}

 

그리고 부모 클래스인 parent를 상속받는 두 개의 자식 클래스 child1, child2 가 있다.

using UnityEngine;

public class child1 : parent // parent를 상속
{
    
}
using UnityEngine;

public class child2 : parent // parent를 상속
{
    
}

 

 

child1, child2가 있는 두개의 게임오브젝트를 만든다.

 

이 상황에서 child1.cs와 child2.cs를 접근할때

public class Test : MonoBehaviour 
{
	private void Start() 
    {
    	// Child1.cs 접근 
    	GameObject.Find("Child1").GetComponent<Child1>();
        // Child2.cs 접근 
        GameObject.Find("Child2").GetComponent<Child2>();
		
    }
}

이런식으로 접근할수도 있지만 Child1과 Child2는 Parent를 상속받았기 때문에

 

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

public class inheritTest : MonoBehaviour
{

    private void Start()
    {
    	// child들은 parent를 상속받았기 때문에 <parent>로도 접근가능하다 
        Debug.Log(GameObject.Find("Child1").GetComponent<parent>().GetType().Name);
        Debug.Log(GameObject.Find("Child2").GetComponent<parent>().GetType().Name);
    }
}

이런식으로 부모의 이름으로도 접근할수 있다.