- Home /
updating a gameobject variable from another script attached to another object
Hi all,
I've seen many posts about this subject but none of these seem to really help. I've been stuck with this for 2 days now...
I have a very simple script named "intersection.js" that is attached to many GameObjects (like the plane named "A1" that is refered to lower) :
All it contains is the following, before functions start and update that are currently empty.
var busy : GameObject;
var back : GameObject;
var front : GameObject;
var left : GameObject;
var right : GameObject;
I want to assign to the variable "busy" a gameobject that this other script (TestMove.js) is tied to :
TestMove.js goes like this:
var targetObj : GameObject;
var targetComp : Component;
function Start () {
targetObj = GameObject.Find("A1");
targetComp = targetObj.GetComponent(intersection);
transform.position = targetObj.transform.position;
targetComp.busy = this; // <--- the problematic line...
}
Then I always get this error message...
Assets/TestMove.js(12,12): BCE0019: 'busy' is not a member of 'UnityEngine.Component'.
Please help a n00b trying to start coding :P
Answer by NickCh · Dec 29, 2012 at 01:41 AM
The way you assign the script is wrong.
function Start(){
var targetObj : GameObject = GameObject.Find("A1");
var targetComp : YourScript =targetObj.GetComponent(YourScript);
yourScript.busy = /*whatever you wanna do here*/ ;
}
Answer by infinitypbr · Dec 28, 2012 at 11:15 PM
I'm not sure about all your code, unfortunately.
But, if you want to assign a GameObject to the variable you've set up, you should be able to just drag-and-drop it in Unity. Otherwise, you could do something like the findbytag option to find it on Start()
Answer by Fuuj1n222 · Dec 29, 2012 at 12:23 AM
Drag & drop works fine, but I need to do it with the script... I have no problem finding the object with GameObject.Find, or getting to the right component using GetComponent()... my problem is accessing/updating the variable.
Anyone have an idea? I know variables are public by default in Unity Javascript, so this shouldn't be the problem. (I tried adding public in front but with no more success)
Is there something special with gameobject variables?
targetObj.GetComponent(intersection).variableName
The game object . GetComponent(script name) . variable you want to access
This is what I do when trying to access the variable named busy but I always get this same errror msg.
Finally I made it work!!!!
targetObj.GetComponent(intersection).busy = this.gameObject;
It's crazy,... I thought I tried this before with no success...
Thank you
Your answer
Follow this Question
Related Questions
Only change a variable on the instaniated object not the prefab. 0 Answers
What is the order of execution for the instantiated object's GetComponent.Script.DoSomething? 1 Answer
Accessing Variables within another gameobject's script 2 Answers
Create a variable on a GameObject for access via the Object without GetComponent() 1 Answer