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.
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.