- Home /
Problem accessing script
I have problems accessing function of another script... Where have I made a mistake?
     if(Input.GetMouseButtonDown(0) && isEquiped)    {
         if(name == "Hackmesser")    {
             print("Hack mit Messer");
             
             var target:RaycastHit;
             
             Debug.DrawRay(Camera.main.transform.position, Camera.main.transform.forward * attackRange,Color.red);
             if(Physics.Raycast (Camera.main.transform.position, Camera.main.transform.forward, target, attackRange)) {
                 if(target.collider.tag == "wache")    {
                     print("Hit Wächter");
                     var guard = target.transform.gameObject.GetComponent(Guard);
                     //var guard = FindObjectOfType(Guard);
                     
                     guard.BeDamaged(DamageAmount);
                 }
             }
         }
     }
 
And here is the Guard.js:
 #pragma strict
 
 var health:int = 100;
 
 function Start () {
 
 }
 
 function Update () {
     if(health<0)    {
         Destroy(gameObject);
     }
 }
 
 function BeDamaged(damage:int)    {
     health = health - damage;
 }
Regards Marc
EDIT: This is the error I get: NullReferenceException: Object reference not set to an instance of an object Item.Update () (at Assets/Scripts/Objects/Item.js:35) 
Answer by Ekta-Mehta-D · Aug 01, 2014 at 11:12 AM
u can try something like :
 Private var guardObj : Guard;
for getting component :
 guardObj = target.transform.gameObject.GetComponent("Guard");
for accessing function :
 guardObj.BeDamaged(DamageAmount);
 
@ekta-mehta-d I get this error: NullReferenceException: Object reference not set to an instance of an object Item.Update () (at Assets/Scripts/Objects/Item.js:35) 
This is the same error I get with my code.
Got my version working! But your version also works.
Answer by Danisuper · Aug 01, 2014 at 11:40 AM
Try GameObject.Find("Guard").GetComponent().guard's_health_variable-=damage 
@Danisuper Assets/Scripts/Objects/Item.js(37,78): BCE0164: Cannot infer generic arguments for method 'UnityEngine.GameObject.GetComponent.()'. Provide stronger type information through arguments, or explicitly state the generic arguments.
Your answer
 
 
             Follow this Question
Related Questions
GetComponent not Returning 1 Answer
C# GetComponent Issue 2 Answers
Accessing script variables of instantiaded prefab 1 Answer
gameObject.GetComponent("Script").enabled = true not working 5 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                