How to change ownership of another object?

1

I have a screen with two objects 2d: player and enemy , both are prefab of an object called fighter .

They have three properties: attack , defense and hp .

I created a script and included it in the camera, it is who will control the game.

I want to know how to make the camera script decrease the hp of one of my objects.

Class fighter :

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

public class fighter: MonoBehaviour {

    public int attack;
    public int defense;
    public int hp;
    public int mp;

    // Use this for initialization
    void Start () {
        int range = Random.Range (150, 200);
        attack = range;
        range = Random.Range (100, 150);
        defense = range;
        range = Random.Range (800, 1000);
        hp = range;
    }

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

    }
}

Class in camera:

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

public class turnBased : MonoBehaviour {

    private BattleStates currentState;

    // Use this for initialization
    void Start () {
    }

    void Update() {
    }

    void OnGUI(){
        if (GUILayout.Button ("ATTACK")) {
        //crio um botão e ao ser clicado, deve causar dano ao inimigo
        enemy.hp -= 10; //<<<<aqui deve vir o código
        }
    }
}
    
asked by anonymous 14.10.2017 / 19:20

2 answers

5

You need to have a local reference for the objects you want to manipulate. There are several ways to get this reference:

  • You can create two public objects of type fighter and assign, via Unity editor (select and drag the player or enemy objects to the turnBased class attribute in the inspector while the camera is selected).
  • You can search for objects internally, using tags or the type of the object (if they were different) or by the name.
  • If you have two objects that are fixed, method 1 is best. In fact, it is the most used and advised in Unity training. But I'll illustrate with Method 2, using the name of the objects to find them.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class turnBased : MonoBehaviour {
    
        private BattleStates currentState;
    
        public fighter player;
    
        public fighter enemy;
    
        // Use this for initialization
        void Start () {
    
            GameObject obj = GameObject.Find("player");
            if(obj != null) {
                player = obj.GetComponent<fighter>();
                if(player == null) {
                    Debug.LogError("Objeto 'player' não tem o componente 'fighter'");
                }
            }
            else {
                Debug.LogError("Não encontrei objeto com o nome 'player'");
            }
    
    
            obj = GameObject.Find("enemy");
            if(obj != null) {
                enemy = obj.GetComponent<fighter>();
                if(enemy == null) {
                    Debug.LogError("Objeto 'enemy' não tem o componente 'fighter'");
                }
            }
            else {
                Debug.LogError("Não encontrei objeto com o nome 'enemy'");
            }
        }
    
        void Update() {
        }
    
        void OnGUI(){
            if (GUILayout.Button ("ATTACK")) {
            //crio um botão e ao ser clicado, deve causar dano ao inimigo
            enemy.hp -= 10; //<<<<aqui deve vir o código
            }
        }
    }
    
      

    In addition, here are some other tips:

         
    • Do not add the game control script to the camera. Create an empty object ( empty ), perhaps called a "gameController", for example, and   add that script there. The camera should only have code related to camera things (translations, rotations, zooms, following character, etc.).
    •   
    • Do not change the enemy's (or player's) HP directly from the control class. Invoke a "Take Damage" method (something like    takeDamage ) passing the total damage. Or make the public attribute    hp become a property really (with getter and setter ). Like this   you have more control over what happens when damage is received   directly in the interested class, and can do other things (touching   animations, for example).
    •   
        
    14.10.2017 / 19:51
    1

    As it was answered, there are several paths, but it would be good to avoid whenever possible to use the means that search (FindObjectOfType, FindGameObjectsWithTag, SendMessage, etc.) for performance.

    You can declare a variable "public GameObject target" within the class Fighter and there in the scene drag the player to the "target" variable of enemy via inspector and vice versa.

    If "targets" change / vary, you can create a method on the newly instantiated enemy that informs the player that it is your new target.

        
    28.11.2017 / 17:14