Editing a variable from another script on collision

My goal is to be able to edit the variable(Current Health) from the first script when my projectile collides with an object containing AIHealth(script 1) from a second script. AI Skelly Prefab contains the AIHealth script. The second script cannot seem to find the variable in the other script.

First Script(AIHealth.cs):

using UnityEngine;
using System.Collections;
public class AIHealth : MonoBehaviour {
	public float MaxHealth=100;
	public float CurrentHealth;
	public bool Dead;
	void Awake () {
	void Update() {

Second Script(Damage.cs):

using UnityEngine;
using System.Collections;

public class Damage : MonoBehaviour {
	public float damage=60;
	public static int CurrentHealth = 100;

void OnCollisionEnter(Collision other){
  		if(other.gameObject.tag == "AI Skelly Prefab"){
				var target = other.gameObject
				var ch = target.transform.GetComponent("AIHealth").CurrentHealth;
    				ch -= damage;


you declared a bool known as dead, you did not set it to false and bools by default are true I believe, so thats actually a bit odd as the object should in fact insta die. :stuck_out_tongue:

the gameobject in this case is what? what exactly did you type for it?

Im wondering if you just ended up trying to destroy the script or something.

For example is you used the keyword this.

so Destroy(this);
That would remove the script.

you need to make sure you pass it the actual AIEnemy

Lastly i dont think that ch variable thing is working, honestly the problem is with unity
I’m not sure if unity is using pointers or not but I think in that case its not.

I think whats happening here is

lets say the aiscript has current health and its equal to 100;


aihealth = 100;
ch = get aihealth;
ch = 100;

ch = ch - 20;

ch = 80

aihealth still equals 100

thats because ch isn't aihealth. its a copy of aihealth.

what you need to do is get rid of what is honestly an unneeded variable anyways

just do 

target.transform.GetComponent<AIHealth>().CurrentHealth -= damage;

you can’t use the string version of getcomponent.

All you need to do is change this line to a type.
dont forget the () after the type.


see this

for that and other common mistakes

Sounds like you should really be using a c# event. If I were you I would set up an entire event messaging system. In this way you can handle Broadcasted events within each script subscribed without outside scripts manipulating your variables (generally frowned upon). Here’s a link to the c# messenger which I believe follows standard design paradigms:

c# advanced messaging system