Doing a Unity assignment for school in C#. I have two capsule objects that share multiple script components (Health, Armor, Weapon) and a third object called Duel. I need the Duel object to call the public variables on the capsule script components. The problem is, I’m not sure how to tell the Duel object to call say, the health on capsule 1 instead of just the public health variable itself.
Easiest way is to expose a public variable for e.g. the health components in the duel script (all in C#):
public HealthClassName playerHealth;
public HealthClassName enemyHealth;
Replace HealthClassName with the name of the health class.
Then in the inspector simply drag and drop e.g. the player gameObject with the HealthClass attached onto the variable slot. Then in the duel script you may call the functions (which need to be public) on the objects directly:
playerHealth.DecreaseHealth(50.0f);
Or, to be more flexible, you may expose the gameObjects instead:
public GameObject player;
public GameObject enemy;
Again, drag the gameObjects into the slots in the inspector.
Awesome, I went with your first suggestion and it worked great. Thanks!
edit: well, almost. I tried making the Duel script do a bit of math i.e. decrease Capsule 1’s health variable by Capsule 2’s damage variable, and I get an error. Here’s the code I have:
P2Health = P2Health - (P1weapon - P2armor)
I can think of one reason why this isn’t working though. The actual variables I want Duel to interact with are PlayerLife (in PlayerHealth script), ArmorRating (in Armor script), and damage (in Weapon script).