์ฝ”๋“œ๋Š” ์„ธ๊ฐœ์ž„


[Player.cs]


using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { [SerializeField] IEnemy target; private void Start() { target = GameObject.Find("Enemy").GetComponent<IEnemy>(); Debug.Log("target = " + target); } private void Update() { if(target != null) { target.GetDamage(3); } } }


=============

[IEnemy.cs]


using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IEnemy { public void GetDamage(int dmg); public GameObject GetGO(); }



============


[EnemyMy.cs]


using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMy : MonoBehaviour, IEnemy { [SerializeField] int hp = 10; public void GetDamage(int dmg) { hp -= dmg; if (hp <= 0) Destroy(this.gameObject); } public GameObject GetGO() { return this.gameObject; } }


==========


๋นˆ ์˜ค๋ธŒ์ ํŠธ 2๊ฐœ ์ƒ์„ฑํ•ด์„œ Player ๋ž‘ EnemyMy ๊ฐ๊ฐ ๋ถ™์—ฌ์ฃผ๊ณ 

์  ์˜ค๋ธŒ์ ํŠธ๋ช…์„ Find()์— ๋“ค์–ด๊ฐ„ Enemy๋กœ ํ•ด์ฃผ๊ณ  ์‹คํ–‰ํ•จ ์ˆœ์‹๊ฐ„์— ์—๋„ˆ๋ฏธ ์ฃฝ๊ณ  ์—๋Ÿฌ ํŒŒํŒŒ๋ฐ• ๋œจ๋Š”๋ฐ VS์—์„œ ์•„๋ž˜์Šค์ƒท์ฒ˜๋Ÿผ ๋ธŒ๋ ˆ์ดํฌ ๊ฑธ๊ณ  ๊ฐ’ ์ฐ์–ด๋ณด๋ฉด null ์ธ๋ฐ๋„ if(target != null) ํ†ต๊ณผํ•˜๋Š” ์žฅ๋ฉด์ด ์žฌํ˜„๋จ



7cf3c028e2f206a26d81f6e44782776b



์ƒ์†์œผ๋กœ ํ•ด๊ฒฐํ•˜๊ธด ํ–ˆ์ง€๋งŒ ์‹ ๊ธฐํ•ด์„œ ๋‚จ๊ฒจ๋ด„