I have an error on a C# script @username
I the line "GetComponents().addforce (Vector2.right * power);" there is an error saying "Type 'UnityEngine.Riidbody2D[]' does not contain a definition for 'addforce'and no extension method ' addforce' of type 'unityEngine.Rigidbody2D[] could not be found. Are you missing an assembly refernce?" How do I fix it? @username
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour {
public int power = 500;
public int jumpHeight = 100;
public bool isFalling = false;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
GetComponents<Rigidbody2D>().addforce (Vector2.right * power);
}
}
Answer by Davirtuoso · Apr 17, 2017 at 12:03 PM
I think the issue is your need to capitalise letters within 'addforce', like so:
GetComponent<Rigidbody2D>().AddForce (Vector2.right * power);
Captilisation matters a lot in c# and 'addforce' is considered a completely different method than 'AddForce'. I hope this helps :)
That is not correct. Using GetComponents returns an Array of the type specified as the generic T, in this case it's Rigidbody2D. The array doesn't have a method/function called AddForce, however each element which is of type Rigidbody2D from the GetComponents call would have a AddForce method/function. For whatever reason the error in the OP has Rigidbody2D spelt incorrectly as well as the case for AddForce.
@Landern Thanks very much for clarifying that. I made the mistake of looking for the simplest issue (aka, casing of AddForce) and posting about that without really looking at anything else in too much detail. Upvoted your answer for more accuracy
Answer by Landern · Apr 17, 2017 at 01:34 PM
There is GetComponent(Singular) and GetComponents(Plural). When you use the plural version (GetComponents) the method/function returns an array of whatever type you specify you're looking for. In this case RigidBody. It seems like you want the singular version which will return a single Rigidbody2D if available on the GameObject.
Change:
GetComponents().addforce (Vector2.right * power);
to
GetComponent().AddForce (Vector2.right * power);
Also @Davirtuoso was correct, you need to specify the methods with exact case.