Hello,
im working on a card game right now.
I’m new to Unity and C#. The things i now come from Tutorials so i hope my question dosn’t sound to stupid.
I made a Hand and a Playfield.
I can drag my cards from my hand to the Playfield.
If i drag a card somewhere else than the hand or playfield it returns to my hand.
On my Playfield i have 9 squares in a square form (3x3)
I made a script that each of this squares can only hold 1 Child. So that i can’t drag more than one card on one square.
The Problem is now, when i drag a card on a square that already has a card on it.
The Card i have dragged disappears (The “Card” gets over my “Canvas” in the Hierarchy) instead of returning to my hand.
Here is the code im using for the Dropzones, Draggable and LimiteChildAmount
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class DropZone : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler {
public Draggable.Slot typeOfItem = Draggable.Slot.INVENTORY;
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("OnPointerEnter");
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("OnPointerExit");
}
public void OnDrop(PointerEventData eventData)
{
Debug.Log("OnDrop to " + gameObject.name);
Draggable d = eventData.pointerDrag.GetComponent<Draggable>();
if(d != null) {
if(typeOfItem == d.typeOfItem || typeOfItem== Draggable.Slot.INVENTORY) {
d.parentToReturnTo = this.transform;
}
}
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public Transform parentToReturnTo = null;
public enum Slot { WEAPON, HEAD, CHEST, LEGS, FEET, INVENTORY };
public Slot typeOfItem = Slot.WEAPON;
public Vector2 dragOffset = new Vector2(0f, 0f);
public void OnBeginDrag(PointerEventData eventData)
{
dragOffset = eventData.position - (Vector2)this.transform.position;
parentToReturnTo = this.transform.parent;
this.transform.SetParent(this.transform.parent.parent);
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
this.transform.position = eventData.position - dragOffset;
}
public void OnEndDrag(PointerEventData eventData)
{
this.transform.SetParent(parentToReturnTo);
GetComponent<CanvasGroup>().blocksRaycasts = true;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LimitChildAmount : MonoBehaviour
{
public int maxChildAmount = 1;
void Update()
{
if (transform.childCount > maxChildAmount)
{
for (int i = maxChildAmount; i < transform.childCount; i++)
{
transform.GetChild(i).SetParent(null);
}
}
}
}
What do i need to change? what am i missing?