- Home /
How can i modify a float in another script in C#?
well i know there's a ton of questions about this but didnt really understand any of them. i simply want this script to say "when i left click, if the raycasted object is tagged enemy then set the enemy's health to -33" but every way i try i get a lot of errors. any ideas?
here is the Raycast script:
 using UnityEngine;
 using System.Collections;
 
 public class WeaponRaycast : MonoBehaviour {
 
     public GameObject Player;
     float isRay = 0;
     public GameObject bulletDecal;
     public GameObject Enemy;
 
     // Use this for initialization
     void Start () {
 
     }
     
     // Update is called once per frame
     void Update () {
         //Debug.Log(isRay);
         RaycastHit hit;
         if(Input.GetButtonDown("Fire1")){
             if(Physics.Raycast(Player.transform.position, Player.transform.forward, out hit, 20f)){
                 if(hit.collider.gameObject.CompareTag("Enemy")){
                     isRay = 1;
                     Enemy.health = -50f;
                 }
                 else{
                     Instantiate(bulletDecal, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));
                     isRay = 0;
                 }
             }
         }
         Debug.DrawRay(transform.position, transform.forward, Color.green);
     }    
 }
and here is the Enemy script:
 using UnityEngine;
 using System.Collections;
 
 public class Enemy : MonoBehaviour {
 
     public static float health = 100f;
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         Debug.Log(health);
         if(health < 100f){
             Destroy(gameObject);
         }
 
     }
 }
 
               Comment
              
 
               
              Answer by TonyLi · Feb 24, 2014 at 05:12 AM
In your Raycast script, you define a variable, but it's unassigned:
 public GameObject Enemy;
Before you use it, you need to assign a value to it. Change this code:
 if(hit.collider.gameObject.CompareTag("Enemy")){
     isRay = 1;
     Enemy.health = -50f;
 }
to:
 if(hit.collider.gameObject.CompareTag("Enemy")){
     isRay = 1;
     Enemy = hit.collider.GetComponent<Enemy>();
     if (Enemy != null) Enemy.health = -50f;
 }
This gets a reference to the Enemy script on the object that was hit. If the reference is non-null, it sets the health to -50.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                