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
CodePudding user response:
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);
}
}
}
CodePudding user response:
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);
}
}