Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Making a Character Controller with C#

Discussion in '2D' started by Darkhalo45, May 7, 2016.

  1. Darkhalo45

    Darkhalo45

    Joined:
    May 7, 2016
    Posts:
    18
    I'm kinda new with Unity, especially with C# and I am trying to make my character to walk, but my script doesn't work! In the Console it says that the object has to be referenced. How do I do that? On line 10 I just wrote rigidbody2D, because everywhere it is written like that.

    public class PlayerController : MonoBehaviour {

    public int speed = 10;

    void Update() {
    if (Input.GetKeyDown ("a")) {
    Rigidbody2D.velocity = new Vector2(-speed, 0);
    }
    }

    }
     
  2. Tom01098

    Tom01098

    Joined:
    Jun 8, 2015
    Posts:
    42
    Alright, so your problem comes from the fact that you are referencing the class rather than an object.

    Make a 'public Rigidbody2D rigidbody2D;' under your speed variable. In the Inspector, you'll notice that a box appears on this script. Drag and drop the object with the Rigidbody2D component onto this slot. Then decapitalize the the Rigidbody2D, and you'll be good to go :)
     
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Tom's method should work, here is an alternative to get the component using code:

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2.  
    3.     public int speed = 10;
    4.  
    5.     private Rigidbody2D myRigidbody;
    6.  
    7.     // called by Unity once when the game first loads
    8.     private void Awake() {
    9.         // gets the Rigidbody2D component on this game object
    10.         // or returns null if there isn't one
    11.         myRigidbody = GetComponent<Rigidbody2D>();
    12.     }
    13.    
    14.     // called by Unity once per frame
    15.     private void Update() {
    16.         if(Input.GetKeyDown("a")) {
    17.             myRigidbody.velocity = new Vector2(-speed, 0);
    18.         }
    19.     }
    20.  
    21. }