I was trying to implement a moving system but there is an error that I don’t know what it means:
Assets\moving_BEAN.cs(14,52): error CS1526: A new expression requires (), [], or {} after type
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moving_BEAN : MonoBehaviour
{
public float speed;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.getAxisRaw("Vertical");
gameObject.transform.position = new vector2;
transform.position.x (h*speed);
transform.position.y (v * speed);
}
}
CodePudding user response:
First of all transform.position
is a Vector3
, You don't overwrite that to a Vector3
.
Second, if You give a value to a variable like that, You close the new ClassName
with ()
, so it looks like this: Classname varname = new Classname()
.
Third, please provide more information regarding your problem. I cannot decide if this is a Unity3D project or 2D.
Fourth, You don't use things like this:
transform.position.x (h*speed);
transform.position.y (v * speed);
You use =
:
transform.position.x = (h*speed);
transform.position.y = (v * speed);
And these 2 line are enough. You don't need the one line it gives the error.
Also, since you move the BEAN in an Update()
method, which is frame-dependant, you should consider doing the following:
transform.position.x = (h * speed * Time.deltaTime);
transform.position.y = (v * speed * Time.deltaTime);
This way the bean will move consistently, not depending on the framerate.
CodePudding user response:
There’s a “syntax” error, and a usage error (or two depending on how you count it).
First, the syntax error is that you’ve missed the parentheses after creating a new struct.
BUT, for your use case, you probably don’t want to be doing this. What would make more sense is to get a copy of the transform’s current position, perform the calculations on that copy, before assigning the whole value back to the transform.position
field.
var pos = transform.position;
pos.x = h * speed * Time.deltaTime;
pos.y = v * speed * Time.deltaTime;
transform.position = pos;
Notice I also modified the position changes by Time.deltaTime
so as to account for the frame rate.
The reason we have to work on a new copy of the position value is because position
is a struct
which is a “value” type. This is in contrast to a “reference” type, which you wouldn’t need to do this with.
CodePudding user response:
Here, on line 14, do this to fix it
gameObject.transform.position = new Vector2();
Does your IDE give you red sqwiggly line? You can click the error to go up to that line.