C# - Cannnot access variable in another script unless I get the component everytime.
Hi !
I have a problem since I got back into scripting, and I can't figure out the solution. I already searched but nothing gave me an answer.
I have a script, in wich I want to access the variable "viewDistance"
 public class AiStats : MonoBehaviour {
 
     public int viewDistance;
 
 }
 
So I did this:
 using UnityEngine;
 using System.Collections;
 
 public class AiBehaviour : MonoBehaviour
 {
     public Component aiStats;
 
     public LayerMask layersToIgnore;
 
     void Start ()
     {
         aiStats = GetComponent<AiStats> ();
     }
 
 
     void Update ()
     {
         Physics2D.Raycast (transform.position, Vector2.up, aiStats.viewDistance, ~(layersToIgnore));
         if (aiAttitude == AiAttitude.Agressive)
         {
 
         }
     }
 }
 
The problem is that I get this error:
Assets/Scripts/AiBehaviour.cs(122,76): error CS1061: Type UnityEngine.Component' does not contain a definition for viewDistance' and no extension method viewDistance' of type UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
But if, instead of putting the AiStats script in a variable, I write :
 Physics2D.Raycast (transform.position, Vector2.up, GetComponent<AiStats>().viewDistance, ~(layersToIgnore));
It works.
But I think it is bad to call GetComponent() so often, so I'd like to reference the Script and use it with that aiStats variable.
Answer by jgodfrey · Feb 24, 2016 at 07:36 PM
Change this:
   public Component aiStats;
To this:
   public AiStats aiStats;
or, if there's no reason for the var to be public...
 private AiStats aiStats;
Your answer
 
 
             Follow this Question
Related Questions
How to fix "no overload for method get component takes 1 arguments" 1 Answer
Error CS0120 : An object reference is required to access non-static member 3 Answers
How to access non static C# variable from another C# script 1 Answer
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                