[Unity] Study_002

APP 2019. 11. 5. 23:40

 

App ---->InGame ------> Character 생성

 

InGame, Character는 Monobehaviour를 상속받고,

Hero, Monster는 Character를 상속받는다.

각각의 Character에 해당하는 Object에는 modeling이 붙어있다.

 

App.cs

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

public class App : MonoBehaviour
{
    public InGame inGame;    
    // Start is called before the first frame update
    void Start()
    {
        GameObject go = new GameObject("InGame");
        this.inGame = go.AddComponent();
        inGame.StartGame();

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

InGame.cs

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

public class InGame : MonoBehaviour
{
    private Hero hero;
    private Monster monster1;
    private Monster monster2;
    private GameObject model1;
    private GameObject model2;         
    void Awake()
    {
        this.model1 = Resources.Load("Boximon Fiery");
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    internal void StartGame()
    {
        this.hero = CreateCharacter("Hero") as Hero;
        this.hero.model = Instantiate(model1);
        this.hero.model.transform.SetParent(this.hero.transform);
        this.hero.hp = 100;
        this.hero.dmg = 20;        

        this.monster1 = CreateCharacter("Monster") as Monster;
        this.monster1.model = Instantiate(model1);
        this.monster1.transform.position = new Vector3(2, 0, 0);
        this.monster1.model.transform.SetParent(this.monster1.transform, false);
        this.monster1.hp = 100;
        this.monster1.dmg = 15;


        this.hero.target = this.monster1;
        this.monster1.target = this.hero;
               
        this.monster1.Attack();
        this.hero.Attack();
    }
    private Character CreateCharacter(string name) where T : Character
    {
        GameObject go1 = new GameObject(name);
        go1.transform.position = new Vector3(0, 0, 0);
        Character character = go1.AddComponent();
        return character;
    }
}

Character.cs

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

public class Character : MonoBehaviour
{
    public new string name;
    public GameObject model;
    public int hp;
    public int dmg;
    public Character target;
    
   
    public void Hit(int dmg)
    {
        this.hp -= dmg;
    }
    public void Attack()
    {
        this.target.Hit(this.dmg);
    }
   
}

Hero.cs

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

public class Hero : Character
{  
}

Monster.cs

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

public class Monster : Character
{
  
}

 

Play를 누르기 전
Play를 누른 후 GameObject Hero의 상태, 체력이 닳았다.
Play를 누른 후 GameObject Monster의 상태, 체력이 닳았다.

: