본문 바로가기

코딩 공부/Unity C#

추상화 연습

문제 1 - 사과에 대한 추상화 결정하기

이 게임에서는 플레이어가 사과와 충돌할 때 사과가 플레이어(뉴턴)에게 체력을 제공해야 합니다. 이 문제를 위해 사과에 어떤 세부 사항이 중요한지 결정하세요.

 

 

문제 2 - 사과 추상화 구현하기

Zip 파일에서 Apple.cs 파일을 스크립트 폴더에 추가하고 Apple 프리팹에 첨부합니다. Apple 스크립트를 열어 이 문제에 대한 사과 추상화에 대해 구현한 필드와 속성을 확인합니다

 

문제 3 - 뉴턴에 코드 추가

뉴턴 스크립트에 코드를 추가하여 사과가 제공하는 체력의 양을 추가하고 뉴턴이 사과와 충돌할 때 콘솔 창에 새로운 체력을 출력합니다. 사과도 파괴하세요.

GetComponent 메서드를 사용하여 게임 오브젝트에 첨부된 스크립트에 대한 참조를 얻을 수 있다는 것을 기억하세요.

 

문제 풀이

Apple Script

public class Apple : MonoBehaviour
{
    const int HealthValue = 10;
    Newton newton;

    private void Start()
    {
        newton = GetComponent<Newton>();
    }


    /// <summary>
    /// Gets the health value for the apple
    /// </summary>
    /// <value>health value</value>
    public int Health
    {
        get { return HealthValue; }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject);
        Debug.Log(newton.Health);
    }

- apple 스크립트에서 사과 제거 및 로그 체력 출력을 모두 하려고 했음

- console 창에서 health를 출력하는 과정에서 계속 오류 발생

 

1차 피드백 후 답안 작성

 

Newton 스크립트

public class Newton : MonoBehaviour
{
    const float MoveUnitsPerSecond = 10;
    int health = 0;

	/// <summary>
	/// Start is called before the first frame update
	/// </summary>
	void Start()
	{
		
	}
	
	/// <summary>
	/// Update is called once per frame
	/// </summary>
	void Update()
	{
		// move as appropriate
        float horizontalInput = Input.GetAxis("Horizontal");
        if (horizontalInput != 0)
        {
            Vector2 position = transform.position;
            position.x += horizontalInput * MoveUnitsPerSecond *
                Time.deltaTime;
            transform.position = position;
        }
	}

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(collision.gameObject);
		health += 10;
		Debug.Log(health);
    }
}

- Newton 스크립트에서 충돌 해결을 하는 편이 간단하다

(충돌한 사과 파괴는 동일하게 구현할 수 있고, healthy를 출력하기 편리함)

- 하지만 healty += 10에서 magic word 사용

 

2차 수정

private void OnCollisionEnter2D(Collision2D collision)
{
    Apple apple = collision.gameObject.GetComponent<Apple>();

    if (apple != null)
    {
        Destroy(collision.gameObject);
        health += apple.Health;
        Debug.Log(health);
    }
}

Apple apple = collision.gameObject.GetComponent<Apple>();:

  • 충돌한 객체(collision.gameObject)에서 Apple 컴포넌트를 가져옵니다

- Apple 스크립트에 있는 프로퍼티 Health에 접근한다