Question by
loafy123 · Apr 20, 2020 at 12:50 PM ·
c#positionc# tutorial
object not in original position when release
I want to make an object that will go back to its original position after dragging it around. But when I release it, the object just went to the bottom left corner of the canvas. This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class needle2 : MonoBehaviour, IPointerDownHandler, IEndDragHandler, IDragHandler
{
private Vector3 startPos;
public Button needles;
public GameObject needleonhand;
public Animator injection;
public bool playing = false;
void Start()
{
needleonhand.SetActive(false);
needles.gameObject.SetActive(true);
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
gameObject.transform.position = startPos;
}
public void OnPointerDown(PointerEventData eventData)
{
gameObject.transform.position = startPos;
}
private void OnTriggerEnter2D(Collider2D OnNeedleTouch )
{
if(OnNeedleTouch.gameObject.name == "patientcure")
{
needleonhand.SetActive(true);
injection.Play("injection");
playing = true;
needles.gameObject.SetActive(false);
}
}
}
Comment
it say 'Field "xx" is never assigned to, and will always have its default value ' warning message
Best Answer
Answer by servo150 · Apr 20, 2020 at 01:31 PM
You don't actually save the start position in the PointerDown event. You are just assigning your current position to whatever startPos is initialized to (maybe Vector2(0,0) which is why it snaps to bottom down when you end dragging.
So that :
public void OnPointerDown(PointerEventData eventData)
{
gameObject.transform.position = startPos;
}
should be
public void OnPointerDown(PointerEventData eventData)
{
startPos = gameObject.transform.position;
}
Thank you for the answer. Learn something today, appreciate it.