How do i create a gameobject, add a script to it, and change a public variable on that script. all from js

How do i create a gameobject, add a script to it, and change a public variable on that script. all from js

Here is my JS:

#pragma strict

function Start () {
	var testobj : GameObject;		
	testobj = new GameObject ("test");
	testobj.AddComponent ("OBJ");
	var targetComp : script = testobj.GetComponent(OBJ);
	OBJ.objPath = "http://www.everyday3d.com/unity3d/obj/monkey.obj" ;
}

function Update () {

}

I get an error about the code before i can run it stating:

Assets/OBJ/src/createobj.js(7,26): BCE0018: The name ‘script’ does not denote a valid type (‘not found’). Did you mean ‘UnityEditor.ScriptCallOptimizationLevel’?

this is a unity3d webplayer app

Any help would be great ty

1 Answer

1

Assuming ‘OBJ’ is the name of the script you are trying to add and that ‘objPath’ is not static, you can do it this way:

#pragma strict
 
function Start () {
    var testobj : GameObject;   
    testobj = new GameObject ("test");
    testobj.AddComponent (OBJ);
    var targetComp : OBJ = testobj.GetComponent(OBJ);
    targetComp.objPath = "http://www.everyday3d.com/unity3d/obj/monkey.obj" ;
}

TY for your quick response. yes your assumptions are correct. However with these changes i get an error stating: > Assets/OBJ/src/createobj.js(7,22): BCE0018: The name 'OBJ' does not denote a valid type ('not found'). And the script im trying to add is OBJ.cs what does the "Bug19" do in this example?

Line 6 seems to have gone funny! I'm assuming it was UA auto-formatting of some kind. // testobj.AddComponent (Bug19); testobj.AddComponent (OBJ); Surely there could be a better name for the script than OBJ zer0c?

Im still getting the error :Assets/OBJ/src/createobj.js(7,22): BCE0018: The name 'OBJ' does not denote a valid type ('not found'). its like its looking for the script that wont be added till runtime.. the script is located under assets:OBJ:src folder

I ran a quick test on the code before I posted it. Since I did not have an 'OBJ' script, I put in a script I did have ('Bug19') and I missed changing one back when I changed them back for posting. As for fixing the 'valid type' problem, on the few occasions I've mixed languages, I tossed the C# in StandardAssets as indicated in the link @alucardj provided.

This was the problem and ty for everyones advise. Problem Solved. and i will be converting this js script to a c# script to unify my project.