Reputation: 9
H, I'm going to develop a drag and drop game with unity but this error appears, how to fix this error, please!
this is the full error ( error CS1061: 'GameObject' does not contain a definition for 'localPosition' and no accessible extension method 'localPosition' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?))
this is my code in the C# script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveSystem : MonoBehaviour
{
public GameObject correctForm;
private bool moving; // to check if it is moving or not
private float startPosX;
private float startPosY;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(moving){
Vector3 mousePos;
mousePos= Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.gameObject.localPosition.z);
}
}
public void OnMouseUp(){
moving = false;
}
public void OnMouseDown(){
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosX = mousePos.x - this.transform.localPosition.x;
startPosY = mousePos.y - this.transform.localPosition.y;
moving = true;
}
}
}
Upvotes: -1
Views: 7947
Reputation: 627
In the update function, in last parameter of last line, you typed this.gameObject.localPosition.z. GameObject has no field named localPosition. You should fix it by this.gameObject.transform.localPosition.z. In conclusion, your Update should looks like this:
// Update is called once per frame
void Update()
{
if(moving){
Vector3 mousePos;
mousePos= Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.gameObject.transform.localPosition.z);
}
}
Upvotes: 1