0

First of all the following code is attachedto an Image element, which has a panel as a parent.

So here is my code:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;

public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public static GameObject item;
public int index;

Transform startParent;
Vector3 startPosition;
bool start = true;

public void OnBeginDrag(PointerEventData eventData)
{   
    item = gameObject;
    startPosition = transform.position;
    startParent = transform.parent;

    GetComponent<CanvasGroup>().blocksRaycasts = false;
    gameObject.GetComponent<LayoutElement>().ignoreLayout = true;
    item.transform.SetParent(item.transform.parent.parent);
}


public void OnDrag(PointerEventData eventData)
{
    #if UNITY_EDITOR
    transform.position = Input.mousePosition;
    #endif

    #if UNITY_ANDROID
    transform.position = Input.touches[0].position;
    #endif
}

public void OnEndDrag(PointerEventData eventData) {
    if(transform.parent == startParent)
        transform.position = startPosition;

    GetComponent<CanvasGroup>().blocksRaycasts = true;
    item.GetComponent<LayoutElement>().ignoreLayout = false;
    item = null;
}

}

and i have two problems i getin the editor an exception that no touch is registred, even though i have the #if UNITY_ANDROID case around it. But the major problem is that i get two null pointer exceptions exceptions when i start draggin and stop draggin in the lines

        gameObject.GetComponent<LayoutElement>().ignoreLayout = true;

        gameObject.GetComponent<LayoutElement>().ignoreLayout = false;

(line 26 and 70)

does anybody know how i canfix any of the problems?

T. Grumser
  • 99
  • 3
  • 18
  • Is `gameObject.GetComponent()` null? – mjwills Nov 30 '17 at 12:33
  • You need to attach `LayoutElement` to the-same GameObject the `DragHandler` script is attached to since you are doing `gameObject.GetComponent` which refers to `this` GameObject. – Programmer Nov 30 '17 at 12:36
  • When id o that the drag and drop stops working. I don#t know exactly whats going on here but every time i try to get rid of any of the exceptions, it results in the menu loosing it functionality – T. Grumser Nov 30 '17 at 13:18

0 Answers0