accessing component functions from main script problems...

I am trying to create a cube without any physics then adding a script that will supply the physics, then alter the physics from the main script.

None of this works so far but here’s what I have.

In the mainscript I have

cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube2.transform.position = Vector3(0,8,4);
cube2.transform.localScale = Vector3(2,2,2);
cube2.AddComponent("addCubePhysics");

//trying to access the addCubePhysics script
	var myphysics : addCubePhysics = gameObject.GetComponent("addCubePhysics");
//hoping it would run a function in addCubePhysics
	myphysics.setvel(Vector3(19,0,0));

in the addCubePhysics script I have

function Start(){
	
gameObject.AddComponent (Rigidbody);  

}

function setvel(myvel){
rigidbody.velocity=myvel;	
}

The errors I am getting are that there is no rigidbody or no gameObject.

I was assuming that if you attach a script that creates a rigidBody to a gameObject then it would create the rigidBody for that game object.

Thanks for any help.

Dan[/code]

The start function may not have run by that point, which is why there wouldn’t be a rigidbody on there to manipulate yet. You can add them at runtime though.

I would suggest changing the start function to an Initialize function, and calling that explicitly before calling the setvel function.

cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube); 
cube2.transform.position = Vector3(0,8,4); 
cube2.transform.localScale = Vector3(2,2,2); 
// Add component returns the component, so this is a better way to store the variable.  Also it's faster to use the type name, rather than a string (I think :P)
var myphysics : addCubePhysics = cube2.AddComponent(addCubePhysics); 

 
//hoping it would run a function in addCubePhysics 
myphysics.Initialize();
myphysics.setvel(Vector3(19,0,0));

addCubePhysics

function Initialize(){ 
    
gameObject.AddComponent (Rigidbody);  

} 

function setvel(myvel){ 
rigidbody.velocity=myvel;    
}

By doing it this way you can be positive the rigidbody has been added before trying to set it’s velocity.

With that code…

I get the error

Object reference not set to an instance of the object.

And the error line is the line

myphysics.Initialize();

I attached the script to the cube2 object
but was using gameObject. to access it.
But gameObject refered to the mainscript not the cube2.

So it works now.
But Start() still does not work.
I guess because it has to wait for the next update()?

Thats right. The start function doesn’t get called until the beginning of the next update loop.

Heres an in depth look at the order the functions get called in. Should help understand whats going on.

http://www.unifycommunity.com/wiki/index.php?title=Updated_Event_Execution_Order