'pls HELP ME HELP ME HELP ME HELP ME [closed]
i was making a game in unity and i got this error: Assets\PlayerController.cs(37,21): error CS0120: An object reference is required for the non-static field, method, or property 'Transform.position'
and this is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace playground
{
public class PlayerController
{
public float speed;
public float JumpHeight;
public Rigidbody rigid;
private Vector3 direction;
void Start()
{
}
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0,
Input.GetAxis("Vertical"));
if(Input.GetButtonDown("Jump"))
{
rigid.AddForce(Vector3.up * JumpHeight,ForceMode.VelocityChange);
}
}
private void FixedUpdate()
{
rigid.MovePosition(Transform.position + direction * speed *
Time.deltaTime);
}}}
pls HELP ME
Solution 1:[1]
You need to wrap your code in a namespace and a class.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Playground
{
public class PlayerController
{
public float speed;
public float jumpHeight;
public Rigidbody rigid;
private Vector3 direction;
void Start()
{
}
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if (Input.GetButtonDown("Jump"))
{
rigid.AddForce(Vector3.up * JumpHeight, ForceMode.VelocityChange);
}
}
private void FixedUpdate()
{
rigid.MovePosition(transform.position + direction * speed * Time.deltaTime);
}
}
}
Solution 2:[2]
As already answered by Matthew M., I would like to add a few more information and points to it.
First, all the code has to be wrapped in a public class
with the name of the script in which the current code is being written. And for the methods Start()
, Update()
, and FixedUpdate()
, these are inherited from Monobehaviour
.
Wrapping in a namespace
is optional, its generally a user preference
public class PlayerController : Monobehaviour
{
public float speed;
public float jumpHeight;
public Rigidbody rigid;
private Vector3 direction;
void Start()
{
}
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0,
Input.GetAxis("Vertical"));
if(Input.GetButtonDown("Jump"))
{
rigid.AddForce(Vector3.up * JumpHeight,ForceMode.VelocityChange);
}
}
private void FixedUpdate()
{
rigid.MovePosition(transform.position + direction * speed * Time.deltaTime);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Matthew M. |
Solution 2 | Geeky Quentin |