How to activate a script function on an instantiated object?

Hi there, I would like to (through Javascript) activate a function on a script attached to an instantiated object via a different script, but I’m not exactly sure how to word it so the editor is happy. This is the part of the code I’m having trouble with:

var z : Transform;

function OnTriggerEnter(hit : Collider){
var zz = Instantiate(z, Vector3(3032.3,2781.8,3068.6),Quaternion.identity);

zz is instantiated from z which already has the script “yesz.” I’m trying to make the “CanWork” variable for zz true.

The editor has a problem with the “zz.CanWork=true;” line, with the MissingFieldException of UnityEngine.GameObject.CanWork.

When I replace the “g” with “G” in “gameObject” in the line above that, the editor has a problem with that line and it says that the object reference is not set to a particular instance of an object.

Could someone please tell me what I’m doing wrong? Thank you.

GetComponent returns an object of the specified type. Refer to the documentation

I suspect you want something like this (assuming yesz is the type of the script):

zz.gameObject.GetComponent(yesz).CanWork = true;

Firstly, I think the compiler might get a bit confused because you are not defining a type for zz. That’s not the main problem here but it’s never a bad thing to define types to your variables. If nothing else, it helps you get better, more descriptive error messages when you do something wrong.

The real problem is exactly what the error says. The class GameObject does not have a variable called CanWork. That variable is in your script yesz where you put it. Since you are not defining the type of zz, the compiler seems to decide it must be a GameObject. Then you are trying to change CanWork on that GameObject.

You are calling GetComponent to get the yesz script on the GameObject but you don’t do anything with the returned yesz script.

     var zz : Transform = Instantiate(z, Vector3(3032.3,2781.8,3068.6),Quaternion.identity);
	 var yeszScript : yesz = zz.gameObject.GetComponent(yesz);
	 yeszScript.CanWork = true;