I recently started working in Unity. I'm pretty new and have only been working with the software for a day, so I was creating a very basic movement script when an error popped up prompting me to close a curly bracket. I did so, but the error persisted. I think my code is fine, what's going on? I'm sure I'm probably just being an idiot.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour {
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
[SerializeField] private float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
CodePudding user response:
The variable "m smoothing" is of type float, and numbers of type float must be accompanied with an f after the end. For example 5 is of type int or float, 5.0 is of type float and should be written 5.0f, and 0.14 is of type float and should be written 0.14f.
The other problem is that you have entered [SerializeField] private in a method. To declare a local variable, that is, it can be called up only in that method, just write the type and name, and if you want, then assign it a value. Learn more, because I have simplified some things, but I hope I have been clear.
Here is your error-free code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14f;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)