I have a Player script and an Enemy script. The Enemy script has a int unitHealth which I did not want to directly call a subtraction from the player script because I was thinking that I wanted to spawn more than one enemy. Note that there will only be one enemy in the game at the time. I tried using tags so that the player script would find the Enemy game object and then subtract its health.
GameObject gameObject = GameObject.FindGameObjectWithTag("Enemy");
gameObject.unitHealth -= 10;
I would get an error saying that unitHealth is not defined for GameObject and Unity would not even let me attach the script to my player.
Maybe I need to tell the GameObject to look for an Enemy script?
Do I have the right idea but wrong code execution or is there a more efficient code to damage my Enemy game object?
You’ve got the right idea, but you’re missing some concepts.
Firstly, “gameObject” is a reserved keyword in Unity for the “current” object. Whatever script you’re writing, “gameObject” will refer to the object that script is attached to. What you currently have will not cause errors (you created a local variable which is okay), but it will be confusing to read as it’s widely known to not use that as a variable name in Unity.
Secondly, “unitHealth” does not exist on the “GameObject” class. It exists on the “Enemy” class. So you need to use GetComponent(); in order to find that component on the GameObject you found with the tag, and then you can access “unitHealth”.
Try this:
GameObject go = GameObject.FindGameObjectWithTag("Enemy");
Enemy enemy = go.GetComponent<Enemy>();
enemy.unitHealth -= 10;
yup
gameObject.GetComponent<Enemy>().unitHealth-=10; // assuming Enemy script is called Enemy :)