Unity/Unity(C#์ค‘๊ธ‰)

์œ ๋‹ˆํ‹ฐ Reflection ์‚ฌ์šฉํ•˜์—ฌ ํƒ€ ํด๋ž˜์Šค๋ฅผ ์ปดํฌ๋„ŒํŠธ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ, ํƒ€ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค์— ์ ‘๊ทผํ•˜๊ธฐ

Rainbow๐ŸŒˆCoder 2021. 12. 15. 11:35
728x90

Reflection์€ ์‘์šฉ ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„์ด ๊ต‰์žฅํžˆ ๋งŽ๋‹ค.

๋งŽ์€ ๋กœ์ง์— ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์„œ ๊ธฐ๋Œ€๋œ๋‹ค.

 

<1>

using System;
using System.Reflection;

์ด๋ ‡๊ฒŒ ๋‘์ค„์„ ์จ์ฃผ์–ด์•ผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

<2>ํƒ€ ํด๋ž˜์Šค๋ฅผ ์ปดํฌ๋„ŒํŠธ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ

- quantity๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์†กํŽธ์ด๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๊ณ  ์•„๋ž˜์™€ ๊ฐ™์ด ์ž‘์„ฑ


public class Songpyeon : MonoBehaviour
{
    public int quantity;
}

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

public class Reflection : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent("Songpyeon") != null)
        {
            Type tp = other.GetComponent("Songpyeon").GetType();
            if(gameObject.GetComponent<Songpyeon>()==null)
            {
                gameObject.AddComponent(tp);
            }
            Invoke("PlusQuantity", 0);
        }
    }
    void PlusQuantity()
    {
        gameObject.GetComponent<Songpyeon>().quantity++;
    }
}

์‚ฌ์‹ค์€ ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ

            Type tp = other.GetComponent("Songpyeon").GetType();
            if(gameObject.GetComponent<Songpyeon>()==null)
            {
                gameObject.AddComponent(tp);
            }

์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•˜์—ฌ๋„ ๋˜‘๊ฐ™์€ ํšจ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

            if(gameObject.GetComponent<Songpyeon>()==null)
            {
                gameObject.AddComponent(Type.GetType("Songpyeon"));
            }

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

public class Reflection : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent("Songpyeon") != null)
        {
            if (gameObject.GetComponent<Songpyeon>() == null)
            {
                gameObject.AddComponent(Type.GetType("Songpyeon"));
            }
            Invoke("PlusQuantity", 0);
        }
    }
    void PlusQuantity()
    {
        gameObject.GetComponent<Songpyeon>().quantity++;
    }
}

<3>ํƒ€ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค์— ์ ‘๊ทผํ•˜๊ธฐ 

์•„๋ž˜์™€ ๊ฐ™์ด ์ž‘์„ฑํ•˜๋ฉด ํŠธ๋ฆฌ๊ฑฐ ์ถฉ๋Œ์ฒด ์•ˆ์— ์†กํŽธ ํด๋ž˜์Šค๊ฐ€ ์žˆ๋‹ค๋ฉด

์†กํŽธ ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค quantity ๋ณ€์ˆ˜๊ฐ€ 50์œผ๋กœ ๋ณ€๊ฒฝ๋œ๋‹ค. 

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

public class Reflection : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent("Songpyeon") != null)
        {
            Type tp = other.GetComponent("Songpyeon").GetType();
            tp.GetField("quantity").SetValue(other.GetComponent("Songpyeon"), 50);
        }
    }

}
728x90