I have a program that should add vertical force to a rigid body when the space key is pressed but I keep getting the same error that says “An item with the same key has already been added”. I can’t seem to get it to go away. Can someone help me fix this?
#pragma strict
function Start () {
var forceSize = 250;
}
function Update () {
if(Input.GetKeyDown(Space)) {
Rigidbody.AddForce(0, forceSize, 0);
}
}
#pragma strict
float forceSize; // Define this in the class scope.
Rigidbody rb; // Declare a variable to store the rigidbody in
function Start () {
forceSize = 250; // You can assign a value here, but it has to be defined in a higher scope so it can be used outside of this Method.
rb = GetComponent<Rigidbody>(); // Get the rigidbody on this object.
}
function Update () {
if(Input.GetKeyDown(Space)) {
rb.AddForce(0, forceSize, 0); // Add force to that stored rigidbody.
}
}
Be aware of SCOPE. You can google more information on this topic, but be declaring var something = 250; in the Start() method you are saying that the variable only exists inside that particular method. To make something accessible in any of this class’s methods you must declare it outside of their scope, at the top of the script.
Also note that Rigidbody is a type. This means that when you say Rigidbody.Addforce it doesn’t make any sense because its kind of like saying “Look at space.” when you should say “Look at this exact point in space which I have stored in a variable.”… Therefore you must first find which specific Rigidbody you want this AddForce to operate on before doing so.