- Home /
Unable to call variable from transform
I'm not doing something right here, I've tried a few ways... but here is what I'm trying to do in general, this code will give anyone the basic idea
     void attackTarget() {
         rct.target.doDamage();
     }
     
     void doDamage() {
         npch.AdjustCurrentHealth(-10);
     }
Basically, I'm trying to do the damage to set target (Cube) which they all have a health-script set to them. I don't understand how to do this correctly.
rct.target is the selected cube. I don't know how to call the NPCH (NPCHealthHandler) from the Transform thing, /:
Basically, what this code ammounts to is this.
 RaycastTargetting.target.NPCHealthHandler.AdjustCurrentHealth(-10);
Answer by aldonaletto · Jan 17, 2013 at 11:08 PM
If NPCHealthHandler is a script, you must get the correct instance with GetComponent. Supposing that rct.target is the target transform (or collider, or gameObject, or any other target reference), you should do the following:
 void attackTarget(){
   NPCHealthHandler npch = rct.target.GetComponent<NPCHealthHandler>();
   if (npch) npch.AdjustCurrentHealth(-10);
 }
This code tries to get the NPCHealthHandler script attached to the object referenced by rct.target - if such script exists in the object, the function AdjustCurrentHealth(-10) is called.
Answer by Bunny83 · Jan 17, 2013 at 11:01 PM
This is the millionth question about Accessing Other Components or other Gameobjects
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                