- Home /
Accessing another script from a class
I am trying to access other variables and functions from inside a class I have created using Javascript. For example:
script 1:
private var x
public function setx(newX)
{
this.x = newx;
}
script 2:
class Class1 {
function doSomething() { script1.setx(1); } };
How would I go about achieving this?
Answer by efge · Feb 22, 2011 at 02:42 PM
You could use the function GetComponent.
Look at the example in the reference.
Answer by Jessy · Feb 22, 2011 at 02:42 PM
You just need a reference to the instance script1.
http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
For example:
private var x;
public function SetX (x) { this.x = x; }
.
class Class1 extends UnityEngine.Object {
function DoSomething () {
(FindObjectOfType(Script1) as Script1).SetX(1);
}
}
I have tried looking at this but I can not work out the correct path to the object. If I just use GetComponent() I get an unknown identifier error because it in a class.
I get the same error "$$anonymous$$ Identifier" because something needs to come before FindObjectOfType. I have tried "Object" but that gives me another error "$$anonymous$$ethod not found". As is not recognised as a keyword. Is it C#?
Sorry. I added in "extends UnityEngine.Object". That will solve it, but you'd be better off deriving from whatever you need, like $$anonymous$$onoBehaviour, perhaps. If you really don't need that, you can use UnityEngine.Object.FindObjectOfType.
Answer by Winston · Feb 22, 2011 at 03:24 PM
I have found the answer. The reference link I needed to use was:
var Script1script = gameObject.GetComponent("script1");
Script1script.SetX(1);
Thanks for the help.
There was no way for us to offer that, given that you did not mention that both scripts were attached to the same Game Object. GetComponent is also a function of Component. No need for "gameObject." But most importantly, don't use that form of GetComponent. (And use PascalCase for class names.) GetComponent.()