How to access variables/functions of another script

I have read in multiple places that
myScript.variableName
should access a variable from another script, or
myScript.function();
should call a function.

Unfortunately it does not seem to work for my scenario.

void OnTriggerEnter(Collider col) {
        if (col.gameObject.tag == "Destroyable") {
            col.gameObject.GetComponent("Disappear").hit = true;
        }
    }

My script name is Disappear and I have certain objects with the Destroyable tag, but I get an error
“‘Component’ does not contain a definition for ‘hit’ and no accessible extension method ‘hit’ accepting a first argument of type ‘Component’ could be found (are you missing a using directive or an assembly reference?)”

Is there any way to either call the disappear() function or edit a boolean variable from another script in this way?

Thanks for the help.

‘GetComponent(string)’ returns the component cast as ‘Component’, so the compiler doesn’t know what members are on it aside from the ones defined on ‘Component’.

What you want to use is the generic version of ‘GetComponent’:

col.gameObject.GetComponent<Disappear>().hit = true;

(it’s the second version of GetComponent in the above link… note how there’s 3 versions, one that takes a ‘type’ object, one that is a generic T, and one that takes string; which you’re using)

This version of the method will return the component cast as the type T you passed in the

Of course, this hinges on ‘hit’ being public.

1 Like