Would this also work for scripts?

posted to: Using Components

So say for example that I wanted to access a  variable or method from another script. Could I declare a variable like

 public script myScript 

Then in the start function make 

myScript = myScript.GetComponent<script>( ); 

and from there on out be able to access any parts of that script just by typing myScript.myVariable  and myScript.myMethod? I tried this but am running into errors. Am I getting the syntax wrong or is GetComponent not the correct way to go about accessing parts of another script?

  • Jonathan Gonzalez(jgonzalez) replied

    Yes that's correct. Scripts you write are considered components as well. Remember when you write it out like:

    myScript.GetComponent<script>();

    you need to manually assign that component. I'm not sure what error you're getting but it may be because you forgot to assign the script to the myScript variable. If you see an error that say something along the lines of "missing reference exception" it's usually because something wasn't properly assigned. If you have any other questions let me know. You can also post the error here and I'll do my best to help explain it. 

  • Hunter & Tiff Eidmann(eithman) replied

    The error comes up as soon as I type 

    public script myScript;


    It underlines the word script in red and says "The type or namespace name 'script' could not be found (are you missing a using  directive or an assembly reference?)

  • Jonathan Gonzalez(jgonzalez) replied

    "script" should be the exact name of your script. I assumed you were just using that name as an example. So for example if I create a script called "PlayerHealth", I would reference it like this:

    public PlayerHealth playerScript;
    void Start ()
    {
    playerScript = playerScript.GetComponent<PlayerHealth>();
    }
    
    

    It says "script cannot be found" because it doesn't actually exist. Hope that helps, if you have any other questions let me know.