- Home /
How can i assign a rigidbody in a script?
i need to constantly reassign a rigidbody that im spawining, and i cant assign it inside of the engine.
Heres my code:
function Update () {
if(Input.GetMouseButtonDown(0))
{
var INHAND : Rigidbody;
INHAND = Instantiate(AssetDatabase.LoadAssetAtPath("assets/ball",Rigidbody),transform.position,transform.rotation);
INHAND.velocity = transform.TransformDirection (Vector3.forward * 2);
}
currently it just says it is null. the prefab im spawing is called ball and is in the assets folder
Is this an editor-only script of some sort? The 'AssetDatabase' only exists in the editor, not other builds. The typical way to solve this problem would be to have a prefab and a variable that is initialized in the inspector. Or to have the prefab in the Resources folder and use Resources.Load().
If you really want to do what you've outlined, this works:
#pragma strict
function Update() {
if(Input.Get$$anonymous$$ouseButtonDown(0))
{
var INHAND : GameObject;
INHAND = Instantiate(AssetDatabase.LoadAssetAtPath("Assets/ball.prefab",GameObject),transform.position,transform.rotation) as GameObject;
INHAND.rigidbody.velocity = transform.TransformDirection (Vector3.forward * 2);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613125047im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how to handle multiple collider in this section? 0 Answers
Spaceship physics - adding resistance 2 Answers
Unity3D Ai wont shoot 1 Answer
Rigidbody AI script needed 0 Answers