Reputation: 1
I'm making a game in Unity3D and I have a 2 different scripts. One called Rays (it checks what I'm clicking on and lowers its hp) and a script called colorChange (it changes the color of the object that I clicked on depending on its hp). I created the hp variable in colorChange and I need to check hp in Ray.
Upvotes: 0
Views: 39
Reputation: 103
So the "colorChange" script depends on the "Rays" script, yes? Then you can define the "colorChange" script to expect a "Rays" component on the same GameObject by using the [RequireComponent] tag, which is described here: https://docs.unity3d.com/ScriptReference/RequireComponent.html
Then in the "Awake" function of "colorChange" you retrieve a reference to "Rays". If the "hp" variable in "Rays" has public get access then in "colorChange" you can use the acquired reference to the "Rays" script to check its current value.
Example for script "Rays":
using UnityEngine;
public class Rays : MonoBehaviour {
private int hp = 0;
public int Hitpoints {
get { return hp; }
}
// ... other methods ...
}
Example for script "colorChange":
using UnityEngine;
[RequireComponent (typeof (Rays))]
public class colorChange : MonoBehaviour {
private Rays raysReference = null;
protected void Awake() {
raysReference = GetComponent<Rays>();
}
protected int getRaysHitpoints() {
return raysReference.Hitpoints;
}
// ... other methods that may use getRaysHitpoints ...
}
Upvotes: 1