- Home /
How can i change a variable on the object hit by a raycast C#
im sure theres a simple solution to this but i dont know it and i dont really know how to phrase the question. i have a simple raycast script here which works fine but i want to know how i can change a float variable on what i hit's script:
void Update () {
RaycastHit hit;
Ray shooterRay = new Ray(transform.position, transform.forward);
if(Input.GetButton("Fire1")){
Debug.DrawRay (transform.position, transform.forward, Color.green);
if(Physics.Raycast(shooterRay, out hit, Mathf.Infinity)){
if(hit.collider.tag == "Enemy"){
Debug.Log("Hit");
hit.EnemyCC.health -= 15;
// EnemyCC is the name of the script i want to change, health is the float
}
}
}
}
Answer by robertbu · Jul 19, 2014 at 01:39 PM
hit.transform.GetComponent<EnemyCC>().health -= 15;
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
AH thanks so much, i was typing other variations on that but i couldnt get it to work, i feel kinda silly now.
Various forms of this problem come up on UA every day, so don't feel silly. The thing to remember is that a script can go on multiple objects, so, unless you've declared variables as static, you need to get the specific instance of that script (component) to access variables or functions.
Answer by sbroscious · Jul 19, 2014 at 02:35 PM
You can also do something like this:
float informationYouWantSent;
if(Physics.Raycast(shooterRay, out hit, Mathf.Infinity)){
hitInfo.transform.SendMessage ("nameOfFunctionOnTargetHitInStringForm", informationYouWantSent, SendMessageOptions.DontRequireReceiver);//this sends the informationYouWantSent to the nameOfFunctionOnTargetHit() if there is no nameOfFunctionOnTargetHit() this code sends no information.
//all the other stuff the Ray does here
}
in your EnemyCC class you would have something like:
float informationExpected;
float informationYouWantToChange;
void nameOfFunctionOnTargetHit(float informationExpected){
//do something to informationYouWantToChange with informationExpected
}
With this method you never have to worry about if the enemy is properly tagged or not, you just need to ensure the gameObject has the nameOfFunctionOnTargetHit() in one of its components if you actually want anything done to the gameObject. You can also send multiple "messages" to multiple gameObjects with the same raycast.
Your answer
Follow this Question
Related Questions
How can i modify a float in another script in C#? 1 Answer
cant kill more than one enemy C# 2 Answers
AI Shooting for Aircraft 1 Answer
Something wrong with the raycast 1 Answer
Float not working all the time? 1 Answer