Hey folks! I’m a beginner in Unity (never used it before). I’ve started a new project today, and wanted to ask you guys what am I doing wrong?
This is the script
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
private Rigidbody2D rb2d;
void Start ()
{
rb2d = GameObject.GetComponent<Rigidbody2D>();
}
void Update ()
{
}
void FixedUpdate()
{
float h = Input.GetAxis ("Horizontal");
rb2d.AddForce((Vector2.right * speed) * h);
}
}
I’ve tried to create a 2D game, and followed instructions of this video:
. That guy has been using Microsoft Visual Studio Assemble C-SHARP. So my question is: Is there a difference between what program do I use to script? (I’m using Assembly CSHARP, but it is developed by Unity), and maybe you can tell me if I’m writing something wrongly?
Sorry for creating a thread (possibly in wrong place), but couldn’t find a place where I can ask help.
I keep getting an error : "
Assets/Scripts/Player.cs(15,35): error CS0120: An object reference is required to access non-static member `UnityEngine.GameObject.GetComponent(System.Type)’
"
Something wrong is with 15th line :c
It would also work if it were gameObject instead of GameObject. Might have just been a typo.
GameObject refers to the class of GameObject while gameObject is a shortcut for “the GameObject this script is attached to”. A further implicit shortcut (via @GroZZleR ) is not even specifying gameObject and just typing GetComponent directly and Unity understands that you are looking on this GameObject.
That’s sort of shorthand though- GetComponent is used on any specific GameObject in your game to find components (scripts) that are attached to it. You need a GameObject reference (a specific GameObject) in order to use it. When you say “GameObject.GetComponent” you’re trying to use it on the class “GameObject” and not on an actual, real object that exists in the scene, and so it tells you “not a static method”. A static method is one that exists for the class as a whole, rather than a specific instance (real object) made from it.
@GroZZleR wrote the way to get a component of the CURRENT GameObject, the one that this script it attached to. You can call it without specifying the specific GameObject it’s referring to because “this.” is implicit. Writing it out the long way, it’s basically: