M
M
Max Bogachov2017-03-12 21:31:53
2D
Max Bogachov, 2017-03-12 21:31:53

What is the error in Unity(CS0236)?

What is the problem?
Everything seems to be correct, but it writes to me

Assets/Scripts/moving.cs(9,23): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `moving.obj'

and
Assets/Scripts/moving.cs(8,23): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `moving.obj'

error, the same as there, whatever.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moving : MonoBehaviour {
  public GameObject obj;
  private float speed = 5f;
  private float xPos = obj.transform.position.x;
  private float yPos = obj.transform.position.y;

  private void Update () {
    if (Input.GetKey (KeyCode.D)) {
      xPos = xPos + speed * Time.deltaTime;
    } else if (Input.GetKey (KeyCode.W)) {
      yPos = yPos + speed * Time.deltaTime;
    } else if (Input.GetKey (KeyCode.A)) {
      xPos = xPos - speed * Time.deltaTime;
    } else if (Input.GetKey (KeyCode.S)) {
      yPos = yPos - speed * Time.deltaTime;
    }
    obj.transform.position = new Vector3 (xPos, yPos,0);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TheTalion, 2017-03-12
@Geekinder

Error description: https://msdn.microsoft.com/en-us/library/5724t6za.aspx
You can do this:
private float xPos;
private float YPos;
void Awake()
{
xPos = obj.transform.position.x;
yPos = obj.transform.position.y;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question