
How to Create a 2D Card Game in Unity – Part 1 (Setup and Basic Game Architecture)
M. S. Farzan
Views: 110457
Like: 1827
Watch the 2021 update to this series:
Check out my books, games and more:
Join our Discord:
Visit our merch store:
Learn how to create a 2D card game in Unity with randomized decks and draggable/droppable cards using the canvas, C# scripting, prefabs, and more!
Continue with Part 2:
Project Git Repository:
Subscribe and like for more!
Take a tour of Unity 2D:
Check out my books and games:
Follow me on Twitter:
Music shout-out: “8bit Blix” by Micah Young
27.01.2022
Try this instead of box colliders, because box colliders dont scale with screen size.
(On the drop zone object)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DropZone : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag != null)
{
eventData.pointerDrag.transform.SetParent(transform);
}
}
}
(on the card)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragDrop : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IBeginDragHandler, IEndDragHandler
{
//Private
[Header("Dragging")]
[SerializeField] private bool isOverDropZone = false;
[Header("Other")]
[SerializeField] private GameObject canvas;
[SerializeField] private GameObject startParent;
[SerializeField] private CanvasGroup canvasGroup;
void Start()
{
canvas = GameObject.FindGameObjectWithTag("Canvas");
canvasGroup = GetComponent<CanvasGroup>();
}
public void OnPointerDown(PointerEventData eventData)
{
startParent = transform.parent.gameObject;
transform.SetParent(canvas.transform);
}
public void OnPointerUp(PointerEventData eventData)
{
transform.SetParent(startParent.transform);
}
public void OnBeginDrag(PointerEventData eventData)
{
canvasGroup.blocksRaycasts = false;
canvasGroup.alpha = .8f;
}
public void OnEndDrag(PointerEventData eventData)
{
canvasGroup.blocksRaycasts = true;
canvasGroup.alpha = 1f;
}
public void OnDrag(PointerEventData eventData)
{
GetComponent<RectTransform>().anchoredPosition += eventData.delta;
}
}
Instead of making an individual prefab for each card and having to make all of the elements separately, you can just make 1 Basic Card with the card functionality and then make variations of that prefab where you can change it
hey i need help, when i change the color in the inspector tab it looks ok but in scene and game tab its not showing like that, also i could only change the color of the canvas and nothing else
This is EXACTLY what I was looking for! Thank you so much!
I love the way you talk. You define everything without jargon, you keep it interesting by explaining like you would in a conversation, and you say funny things sometimes 😀 "Nice white background so we are playing in the snow" "Yay us" "An angry tuna red" "I'm going to name it drag and drop… and now i am going to drag and drop it" Also thanks for explaining every little detail, i learned some easier ways to do things that i didn't know before 🙂 The video feels a little long but it is completely worth it!
The Drag and Drop condition simply doesn't work. Great tutorial, but it is sad that it doesn't work without a proper reason. I did exactly what it you did through the whole video and still…
Why did when i type the GameObject playerCard, the playerCard didnt go to color blue for its font in visual studio?when in ur video it should be in blue? And when i set its parent it wont do it but it does exist?
Making my own card game is on my bucket list! Haha!
U know instantiate method has override argument (prefab, gameobject parent)
Hello! Thank you 4 the tutorial! It's really good and really helpful! Спасибо!
Hello Farzan,
Thank you for this tutoriel.
I liked the way you introduced the concept of layers and colliders it makes a lot of sense and it's usefull for advanced use case scénarios. 🙂
I did a simpler mechanism to detect if the card is inside the dropZone I want to know what you think about it.
Instead of checking for collisions or raycasting I check if the dropZone and the card are overlapping by using the "Rect.Overlaps" method only when the "End Drag" event is triggered.
This way it could be more efficient since we don't rely on any raycasting/collision engine and the computation is done only once.
I paste the code here and I hope you find this relevant.
Thanks again for this tutorial 🙂
using UnityEngine;
public class DragDrop : MonoBehaviour
{
private bool isDragging = false;
public GameObject dropZone;
private Vector2 startPosition;
void Start()
{
dropZone = GameObject.Find("DropZone");
}
void Update()
{
if (isDragging)
{
transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}
}
private Rect GetWorldSpaceRect(RectTransform rt)
{
var r = rt.rect;
r.center = rt.TransformPoint(r.center);
r.size = rt.TransformVector(r.size);
return r;
}
private bool rectOverLaps(RectTransform transf1, RectTransform transf2)
{
Rect rect1 = GetWorldSpaceRect(transf1);
Rect rect2 = GetWorldSpaceRect(transf2);
return rect1.Overlaps(rect2, true);
}
public void StartDrag()
{
startPosition = transform.position;
isDragging = true;
}
public void StopDrag()
{
if (rectOverLaps(transform.GetComponent<RectTransform>(), dropZone.GetComponent<RectTransform>()))
{
transform.SetParent(dropZone.transform, false);
} else
{
transform.position = startPosition;
}
isDragging = false;
}
}
Good God, you should be a code bootcamp teacher. Thanks!
bro i dont have cards layer in my project settings..! HELP…!
Excellent tutorial.
Subscribed.
Amazing tutorial. Helped me so much! I have a small question: I want the "Draw Cards Button" to act more like a "Shuffle Button" (click on button: draw 5 cards, click again: draw 5 new cards). When I click on the button twice it just duplicates the cards so I end up with ten. Do you know how I can change the script to accomplish that?
I am looking to recreate the in game Gwent from Witcher 3. I have no programming background whatsoever. Will be a humongous task for me.
This Tutorial is so amazing. It describes Object oriented development, Lists, technics of development i used in many projects, its realy good structure. The relationship between Editor/Stage instances. Its amazing.
Everyone gangsta till he pulled out the unity physic system
Thanks from Austria👍👍❤
THANK YOU for this tutorial, and for doing such an amazing job explaining in plain terms what each line of script accomplishes. More than a lesson in how to create and program a card game, I feel like I have a better understanding of C# after watching this video.
I got the error "Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption." when trying to first get the Button with the OnClick method to work (~time 28:23). Based on googling, i can't make out if it is by design or a bug (would seem in some versions it's a bug, some by design). Help!
Setting the parent of a transform which resides in a prefab asset is disabled to prevent data corruption.
someone can help me pls? 🤔
32:00 why not horizontal layout?
I'm new to Unity but I learned a lot from this video
Hi thanks for the video, I am getting below error
UnassignedReferenceException: The variable Card1 of DrawCards has not been assigned.
You probably need to assign the Card1 variable of the DrawCards script in the inspector.
I can't click and drag the game object from the hierarchy to the inspector for the script
27:39–28:50
The card1 does not appear.
Error infromation: setting the parent of a transform which resides in a prefab is disabled to prevent data corruption (GameObject: 'card1(Clone)')UnityEngine, Stack TraceUtility:ExtractStack Trace()
How to solve this error?
so I accidentally deleted my game and then unity… TO remaking!!!
Thats a hell lot of "eh, ah, uh, uhm" and struggling to explain certain things for an 1 hour video but the tutorial is awesome
This was very helpful – I have wanted to make a card game and for a while there were not many tutorials when I tried a year or so ago. I as a beginner in Unity and C# – I was able to follow along quite easily. I look forward to learning more! Thanks for the guidance!
Just started today with unity 2D, this is the coolest things i saw! just what i wantad! i have an idea for a card game and this can help me to learn
Min 27:00 ..i have a problem call "Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption" want to draw the cards with the button …im super noob, help!
Watched LOADS of tutorials,
yours are 12/10
wish you would have been my teacher back in college
Question: What if I have only one scriptable prefab 'Card' game object, but I have stored a lot of scripts in my database, how will I make the random range work for just one prefab card?
Can Unity and C# help me create a web-based virtual tabletop (VTT) for RPGs like Pathfinder (i.e. Dungeons & Dragons)?
Timestamps woulda been great
Thank you very much! ! This tutorial makes it easier for me to get started with Unity !!
why do i get this error at 23:05:
'DrawCards.OnClick()' must declare a body because it is not marked as internal external or partial
I have no idea what you're doing, but Unity isn't letting me do most of the things you're able to do. Around 25 minutes in, I had about 26 Errors and I couldn't even do the part you were doing because It wouldn't let me.
I'm just learning Unity and your videos are really well explained, I understood most of your video!
what a great video. clear explanation
This is so useful, the way that things are explained, for example showing that just because you have the first onclick instatiate function to add the card clone but having it not work because its not nested under the canvas, is so incredibly insightful to someone that's brand new and learning unity like myself.
lit <3
11:33 I'm surprised you came up with 177 off the top of your head from "previous experience with Unity" LOL!! Love the video, great stuff!!
So helpful. Thank you so much!
I want to make a question, why you create all the objects as canvas' childs? I don't understand when you have to use the canvas or not. People usually say "it's for UI things" but, it's a card an 'UI thing'?
51:25 suddenly this game is pansexual.
Great tutorial btw.
Usuario le ha dado al botón de no me gusta.
Clear tutorial, it seems to do fine untill you try to use the first script in combination with the latest unity. it won't allow you to set the parent of the transform for some reason.
Quaternion.Identify wasn’t working is that because your on an older version