I’ve worked this code using only 1 object as a public game object, but now i would like to use tags for multiple objects. It wont recognise hit info on line 19, can anyone help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAbilities : MonoBehaviour {
public int TreeHealth = 100;
public int ObjectDamage = 10;
public GameObject Tree;
public int Wood = 0;
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, 5)) {
if (hitInfo.collider.tag == "tree") {
if (Input.GetMouseButtonDown(0)){
TreeHealth -= ObjectDamage;
Wood += 5;
Debug.Log(TreeHealth);
}
}
}
if (TreeHealth <= 0) {
Destroy(Tree);
}
if (Input.GetKeyDown(KeyCode.Tab)) {
Debug.Log("Wood: " + Wood);
}
}
}
It seems odd that your player would have the tree health in it. I would think that the health would be on your tree, or else all trees will share the same health. You’d still check if the tag is tree, and if mouse button is down, but you would probably want to call some sort of function from the tree you collided with to reduce its health, and in the tree somewhere (update, for example), still check if it’s health is <0, and destroy it. Don’t do that in the player unless you only have one tree in your whole game, which I doubt you do
And that said, I told you how to do this all in your tree using OnMouseDown. That would be a lot easier… not sure why you preferred this approach, but it’s up to you.
That said, I think there might be a bit of debate as to just how much faster it is (unless you’re repeating a lot of checks), although, I think any time you can avoid extra garbage collection, you should.
That said, I think using layers / layer masks for collisions is the even quicker solution, but I didn’t want to add more confusion.