Home > Software engineering >  Obtaining data from selected object
Obtaining data from selected object

Time:05-28

I'm looking for a way to obtain data from an object I have "selected/targeted" in game. Example: I want to select an enemy to attack and then take the hp value from the script attatched to them and compare it to the attack value on the player script. I've looked around on google and youtube but have found no luck. Hoping someone could help me or point me to a guide to look at.

Example in code form: Script 1:

public class Enemy : MonoBehaviour
{
public int enemyHealth;
}

Script 2:

public class Player : MonoBehaviour
{
    public Enemy enemy;
    public int playerAtk;
}

public void Attack()
{
    "Selected enemy's enemy script".health -= playerAtk;
}

CodePudding user response:

You must access the enemy through a specific event. For example, when hitting a bullet or clicking the mouse on it. Below are some examples of how to get the enemy, but keep in mind that there are countless ways to access the enemy.


On Trigger Enter

This is a very simple way, This code works in the player class. The collider key gives you access to the enemy, now you can access the methods by holding its component.

public void OnTriggerEnter(Collider other)
{
    var _enemy = other.GetComponent<Enemy>(); // // Get Enemy class

    _enemy?.Damage(10); // damage method run.

    _enemy?.Damage(this, 10f); // Send player to method and cause damage
}

Physics Raycast

This will happen by throwing a ray from the camera, what the raycast code does is return the point of impact in raycastHit format. After getting it, you can access your other raycastHit components as shown below.

public void Update()
{
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (!Input.GetKeyDown(KeyCode.Mouse0)) return;

    if (Physics.Raycast(ray, out var RaycastHit))
    {
        var _enemy = RaycastHit.transform.GetComponent<Enemy>();

        _enemy?.Damage(10);
    }
}

Specify in the Inspector

In this method, you can put all the enemies in an array and damage them by calling the index.

public Enemy[] myEnemy;

public void Damage(int index)
{
    myEnemy[index].Damage(10);
}

Find By Type

Another popular method is to capture all enemies and filter them based on a specific condition. This method is also performed in this way.

var enemies = FindObjectsOfType<Enemy>();

foreach (var _enemy in enemies.Where(e => e.health >= 40f))
{
    _enemy.Damage(100);
}
  • Related