Changing a variable in another script on Raycast hit - C#
I'm trying to have a variable (Health), in the script of another game object, change when a RayCast hits said object. Here's what I have so far:
void Update () {
Debug.DrawRay (this.transform.position, this.transform.forward * RaycastDistance, Color.red);
if(Physics.Raycast(this.transform.position, this.transform.forward, out WhatIHit, RaycastDistance))
{
Debug.Log ("I hit " + WhatIHit.collider.gameObject.name);
WhatIHit.collider.GetComponent
}
}
What would I need to add after "GetComponent" to have the Health value in the other object subtract by 5 every time the raycast hits the object?
Answer by Commoble · Apr 20, 2017 at 05:56 PM
// get a component of type ScriptType from the hit object
ScriptType script = WhatIHit.collider.GetComponent<ScriptType>();
// make sure the hit object has this component
if (script != null)
{
script.health -= 5; // 5 if it's an integer, 5F if it's a float
}
Alright, I've got this so far. I don't know if it's right though. Also, I don't know where I would put the ScriptType line.
void Update () {
Debug.DrawRay (this.transform.position, this.transform.forward * RaycastDistance, Color.red);
if(Physics.Raycast(this.transform.position, this.transform.forward, out WhatIHit, RaycastDistance))
{
Debug.Log ("I hit " + WhatIHit.collider.gameObject.name);
}
if (Statistics != null) {
Statistics.Health -= 5;
}
}
What is the "using directive" for ScriptType? Or must we create the directive manually? @Commoble
What is the "using directive" for ScriptType? Or is ScriptType a directive that needs to be created manually?
Your answer
Follow this Question
Related Questions
About AI detecting a sound 1 Answer
Variable changing from other script does not work. 1 Answer
Enemy Variable Battle System 1 Answer
C# Unity dot syntax exercise correct solution? 1 Answer
Beginner needs Help! 1 Answer