finalcommit

This commit is contained in:
Nim XD
2024-02-16 00:42:43 +05:30
parent 352ec1b5f3
commit 5133ebc30c
45 changed files with 209225 additions and 1680 deletions

BIN
Assets/.DS_Store vendored

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,140 @@
fileFormatVersion: 2
guid: 80e882e0758d243f3b6a785254be4251
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

@@ -0,0 +1,140 @@
fileFormatVersion: 2
guid: 701d43673de4646f69d0df768c93cfe3
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -49,26 +49,52 @@ using Mirror;
private void SetDirection()
{
Vector2 direction;
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
direction = Vector2.left;
if(joystick.Input == Vector2.zero){
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
direction = Vector2.left;
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
direction = Vector2.right;
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
direction = Vector2.up;
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
direction = Vector2.down;
}
else return;
}else{
direction = JoyToDir();
// direction= joystick.Input;
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
direction = Vector2.right;
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
direction = Vector2.up;
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
direction = Vector2.down;
}
else return;
Debug.Log(direction);
Character.SetDirection(direction);
}
Vector2 JoyToDir(){
if(joystick.Input == Vector2.zero){return Vector2.zero;}
Vector2 direction;
if(Mathf.Abs(joystick.Input.x) > Mathf.Abs(joystick.Input.y)){
if(joystick.Input.x > 0){
direction = Vector2.right;
}else{
direction = Vector2.left;
}
}else{
if(joystick.Input.y > 0){
direction = Vector2.up;
}else{
direction = Vector2.down;
}
}
return direction;
}
private void Move()
@@ -98,6 +124,10 @@ using Mirror;
direction += Vector2.down;
}
if(joystick.Input != Vector2.zero){
direction = joystick.Input;
}
if (direction == Vector2.zero)
{
if (_moving)
@@ -118,7 +148,7 @@ using Mirror;
private void Actions()
{
if (Input.GetMouseButtonDown(0))
if (Input.GetKeyDown(KeyCode.Space))
{
playerNet.OnAttack();
}

28
Assets/MenuSceneScript.cs Normal file
View File

@@ -0,0 +1,28 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuSceneScript : MonoBehaviour
{
public TMP_Text usernameUI;
void Start()
{
}
void Update()
{
usernameUI.text = gplayAuth.userNameCloud;
}
public void LoadGameScene(){
SceneManager.LoadScene("Game");
}
public void LogoutBacktoLogin(){
SceneManager.LoadScene("GameLogin");
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 18a59194b23514d06b81e36cef29eb11
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -100,7 +100,7 @@ MeshRenderer:
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 0}
- {fileID: 2100000, guid: 2613116b8a9839f4eb8abb181b83477e, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
@@ -219,7 +219,7 @@ BoxCollider2D:
m_IsTrigger: 0
m_UsedByEffector: 0
m_UsedByComposite: 0
m_Offset: {x: -0.25490236, y: 1.9914019}
m_Offset: {x: -0.23830795, y: 1.7507877}
m_SpriteTilingProperty:
border: {x: 0, y: 0, z: 0, w: 0}
pivot: {x: 0, y: 0}
@@ -230,7 +230,7 @@ BoxCollider2D:
adaptiveTiling: 0
m_AutoTiling: 0
serializedVersion: 2
m_Size: {x: 4.512574, y: 4.974426}
m_Size: {x: 3.450554, y: 3.663494}
m_EdgeRadius: 0
--- !u!114 &1503341026146379345
MonoBehaviour:
@@ -250,8 +250,8 @@ MonoBehaviour:
health: 100
healthBar: {fileID: 3653340846896160726}
speed: -0.5
chaseRadius: 4.4
attackRadius: 2.35
chaseRadius: 4.2
attackRadius: 2.4
rotate: 0
target: {fileID: 0}
animator: {fileID: 2791034258113794106}

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 199b3ccaad9604955a93baa58e6daaa1
guid: 8f7fc7ae237f341739c369fc7d9f4b75
DefaultImporter:
externalObjects: {}
userData:

File diff suppressed because it is too large Load Diff

196679
Assets/Scenes/MenuScene.unity Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a141cf40801414f09a4017e4a9f84683
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -25,6 +25,28 @@ public class Inventory : MonoBehaviour
}
}
public Dictionary<string, int> getInventoryDictionary (){
Dictionary<string, int> invDictionary = new Dictionary<string, int>();
foreach(LootData loot in lootDatas){
if(invDictionary.ContainsKey(loot.type)){
invDictionary[loot.type]+= loot.count;
}
else{
invDictionary.Add(loot.type, loot.count);
}
}
return invDictionary;
}
public void setInventoryData(Dictionary<string, int> invSetData){
foreach(LootData loot in lootDatas){
if(invSetData.ContainsKey(loot.type)){
loot.count += invSetData[loot.type];
}
}
}
private void UseItem(int index){
if(playerNet.health >= 100){
return;
@@ -58,11 +80,12 @@ public class Inventory : MonoBehaviour
if(RemoveItem(lootDatas[index].type)){
playerNet.DropPickup(lootDatas[index].type);
}else{
Debug.LogError("No items to drop in slot " + index);
Debug.Log("No items to drop in slot " + index);
}
}
public void AddItem(string type){
playerNet.SavePlayerData();
foreach(LootData loot in lootDatas){
if(loot.type == type){
loot.count++;
@@ -74,6 +97,7 @@ public class Inventory : MonoBehaviour
}
public bool RemoveItem(string type){
playerNet.SavePlayerData();
foreach(LootData loot in lootDatas){
if(loot.type == type){
if(loot.count <=0){return false;}

View File

@@ -13,6 +13,7 @@ public class PlayerAttack : NetworkBehaviour{
public float attackRange;
public Vector3 castOffset;
public int damage;
public playerNetwork pnet;
public GameObject leftAnim,rightAnim,upAnim,downAnim;
@@ -35,7 +36,7 @@ public class PlayerAttack : NetworkBehaviour{
}
IEnumerator couroutineAttack(){
yield return new WaitForSecondsRealtime(0.2f);
yield return new WaitForSecondsRealtime(0.6f);
Attack();
}
void Attack(){
@@ -47,8 +48,9 @@ public class PlayerAttack : NetworkBehaviour{
if(hit.collider == null){return;}
if(hit.collider.transform.GetComponent<enemyScript>() != null){
hit.collider.transform.GetComponent<enemyScript>().TakeDamage(damage, netId);
Debug.Log("Attacked enemy");
int damageamount = damage + (pnet.lvl*5);
hit.collider.transform.GetComponent<enemyScript>().TakeDamage(damageamount, netId);
Debug.Log("Attacked enemy " + damageamount);
}else{
Debug.Log("Not an enemy : " + hit.collider.transform.name);
}

128
Assets/Script/joystick.cs Normal file
View File

@@ -0,0 +1,128 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class joystick : MonoBehaviour
{
public bool touchDown;
public bool autoConfigMaxDist;
public float maxDist;
public Vector2 input;
public Vector2 deltaPos;
public Vector2 startPos;
public Vector2 endPos;
public RectTransform joyBG;
public RectTransform joyStick;
public static Vector2 Input => instance.input;
public static joystick instance;
void Awake(){
instance = this;
}
void Update()
{/*
if (autoConfigMaxDist)
{
maxDist = joyBG.sizeDelta.x / 2;
}
if (touchDown)
{
if (Input.touchCount > 0)
{
Touch[] tlist = Input.touches;
int tId = 0;
for (int i = 0; i < tlist.Length; i++)
{
if (tlist[tId].position.x < Screen.width / 2)
{
tId = i;
continue;
}
}
if(tlist[tId].position.x > Screen.width / 2) { return; }
endPos = tlist[tId].position;
}
else if (Input.mousePosition.x < Screen.width / 2)
{
endPos = Input.mousePosition;
}
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
}
else
{
// deltaPos = Vector2.zero;
}
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if(_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
*/
}
public void onDrag(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
endPos = ped.position;
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if (_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
}
public void pointerDown(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
startJoy(ped);
}
public void pointerUp()
{
endJoy();
}
void startJoy(PointerEventData pointer)
{
startPos = pointer.position;
joyBG.gameObject.SetActive(true);
joyStick.gameObject.SetActive(true);
joyStick.localPosition = Vector2.zero;
joyBG.position = startPos;
touchDown = true;
}
void endJoy()
{
// joyBG.gameObject.SetActive(false);
// joyStick.gameObject.SetActive(false);
input = Vector2.zero;
touchDown = false;
joyStick.localPosition = Vector2.zero;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4c3e2498228fa499982a8458095f71c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -65,7 +65,7 @@ public class playerChat : NetworkBehaviour
[Command]
private void CmdSendMessage(string message)
{
RpcHandleMessage($"[{connectionToClient.connectionId}]: {message}");
RpcHandleMessage($"[{gplayAuth.userNameCloud}]: {message}");
}
[ClientRpc]

View File

@@ -4,6 +4,8 @@ using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Enums;
using Mirror;
using TMPro;
using Firebase.Firestore;
using Firebase.Extensions;
using Unity.VisualScripting;
using UnityEngine;
@@ -19,8 +21,33 @@ public class playerNetwork : NetworkBehaviour
[SyncVar]
public int enemyKillCount;
public int xp { get{
int val = 0;
for(int i =5; i <= enemyKillCount; i+=5){
val = enemyKillCount;
}
return val;
}}
public int lvl { get{
int val = 0;
for(int i =5; i <= enemyKillCount; i+=5){
val ++;
}
return val;
}}
[SyncVar]
public string playerName;
[SyncVar]
public int playerCoin;
public TMP_Text txtEnemyKillCount;
public TMP_Text txtPlayerName;
public TMP_Text questText;
public TMP_Text coinText;
public TMP_Text xpText;
public TMP_Text lvlText;
public TMP_Text xpEnableTxt;
public TMP_Text attackDmgEnableTxt;
public GameObject canvas;
public healthBar healthBar;
@@ -30,10 +57,80 @@ public class playerNetwork : NetworkBehaviour
void Start(){
if(!isLocalPlayer){
LoadPlayerData();
if(isServer){
playerName = gplayAuth.userNameCloud;
}
else{
CmdSetName(gplayAuth.userNameCloud);
}
canvas.SetActive(false);
}
}
public void SavePlayerData(){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
//int playerCoin = int.Parse(coins.text);
Dictionary<string, object> saveValues = new Dictionary<string, object>{
{"playerInventory" , inventory.getInventoryDictionary()},
{"playerHealth" , health},
{"playerCoin", playerCoin},
{"killCount", enemyKillCount},
};
DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
if(task.IsCompleted){
Debug.Log("Save Completed Firestore");
}
else{
Debug.Log("Failed to save data to firestore");
}
});
}
public void LoadPlayerData(){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
DocumentSnapshot snapshot = task.Result;
if(snapshot.Exists){
//load data
// Dictionary<string,object> dic = snapshot.ToDictionary(ServerTimestampBehavior.Estimate);
// Debug.Log("Reading data");
// foreach(KeyValuePair<string,object> item in dic){
// Debug.Log(item.Key + " : " +item.Value.ToString());
// }
//saveNameTxt.text = snapshot.GetValue<string>("playerName");
enemyKillCount = snapshot.GetValue<int>("killCount");
//Load coin
playerCoin = snapshot.GetValue<int>("playerCoin");
coinText.text = snapshot.GetValue<int>("playerCoin").ToString();
//Load Health
int savedHealth = snapshot.GetValue<int>("playerHealth");
SetHealth(savedHealth);
healthBar.SetHealth(savedHealth);
//load Inventory
Dictionary<string, int> inventoryGetData = snapshot.GetValue<Dictionary<string,int>>("playerInventory");
inventory.setInventoryData(inventoryGetData);
}else{
//show error previous data doesnt exists to load
Debug.Log("No previous data to load");
}
});
}
void CmdSetName(string nameValue){
playerName = nameValue;
}
void OnDirectionChanged(Vector2 oldVal, Vector2 newVal){
character.SetDirection(newVal);
}
@@ -54,7 +151,10 @@ public class playerNetwork : NetworkBehaviour
healthBar.SetHealth(health);
txtEnemyKillCount.text = enemyKillCount.ToString();
txtPlayerName.text = playerName;
}
ShowXP();
ShowLevel();
}
@@ -73,6 +173,7 @@ public class playerNetwork : NetworkBehaviour
}
void OnHealthChanged(int oldVal, int newVal){
SavePlayerData();
if(!isLocalPlayer){return;}
healthBar.SetHealth(newVal);
}
@@ -107,10 +208,51 @@ public class playerNetwork : NetworkBehaviour
death();
}
}
public void ShowXP(){
xpText.text = xp.ToString();
}
public void ShowLevel(){
lvlText.text = lvl.ToString();
}
public void OnEnemyKilled(){
int prevValue = lvl;
SavePlayerData();
enemyKillCount++;
if(lvl > prevValue){
StartCoroutine(uiTxtDelay(25f));
}
if(enemyKillCount == 5 ){
SavePlayerData();
QuestComplete();
AddCoin();
}
}
IEnumerator uiTxtDelay (float delayTime){
//enable
xpEnableTxt.gameObject.SetActive(true);
attackDmgEnableTxt.gameObject.SetActive(true);
yield return new WaitForSecondsRealtime(delayTime);
//disable
xpEnableTxt.gameObject.SetActive(false);
attackDmgEnableTxt.gameObject.SetActive(false);
}
public void QuestComplete(){
//task completion logic
// Strikethrough the text
questText.text = "<s>Kill 5 Enemies to claim 100Golds</s> Completed";
Debug.Log("First quest completed");
}
public void AddCoin(){
playerCoin += 100;
coinText.text = playerCoin.ToString();
}
[ClientRpc]
public void RpcDeath(){
death();
@@ -197,6 +339,7 @@ switch (character.WeaponType)
}
void pickupObject(string type){
inventory.AddItem(type);
}

View File

@@ -12,6 +12,7 @@ using System;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
using TMPro;
using UnityEngine.SceneManagement;
public class gplayAuth : MonoBehaviour{
@@ -19,13 +20,25 @@ public class gplayAuth : MonoBehaviour{
public TMP_Text gplayText;
public TMP_Text firebaseStatText;
public string AuthCode;
public static string userID;
bool IsConnected;
public TMP_InputField saveName, coins, item1, item2, item3 ;
public TMP_Text saveStatText;
public TMP_Text saveNameTxt , coinsTxt, item1Txt, item2Txt, item3Txt;
void Start() {
IsConnected =false;
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false)
.RequestEmail().RequestIdToken().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
//GPGSLogin();
}
public static string userNameCloud;
public void GPGSLogin(){
PlayGamesPlatform.Instance.Authenticate((success) => {
if(success == true){
@@ -36,6 +49,7 @@ public class gplayAuth : MonoBehaviour{
if(task.Result == Firebase.DependencyStatus.Available){
//no dependency issue with firebase, continue to login
ConnectToFirebase();
}
else{
//error with firebase Dependecies plugin
@@ -54,7 +68,148 @@ public class gplayAuth : MonoBehaviour{
);
}
public void SaveData(){
//checking if connected to firebase
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
string playerName = saveName.text;
int playerCoin = int.Parse(coins.text);
List<string> plyaerInventoryItems = new List<string>();
plyaerInventoryItems.Add(item1.text);
plyaerInventoryItems.Add(item2.text);
plyaerInventoryItems.Add(item3.text);
Dictionary<string, object> saveValues = new Dictionary<string, object>{
{"playerName" , playerName},
{"playerCoin" , playerCoin},
{"playerInventory" , plyaerInventoryItems},
};
DocumentReference docRef = db.Collection("PlayerData").Document(userID);
docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
if(task.IsCompleted){
saveStatText.text = "Save Completed Firestore";
}
else{
saveStatText.text = "Failed to save data to firestore";
}
});
}else{
//firebase_Not_Connected_error
Debug.LogError("firebase Not connected to save");
}
}
public void LoadData(){
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("PlayerData").Document(userID);
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
DocumentSnapshot snapshot = task.Result;
if(snapshot.Exists){
//load data
Dictionary<string,object> dic = snapshot.ToDictionary(ServerTimestampBehavior.Estimate);
Debug.Log("Reading data");
foreach(KeyValuePair<string,object> item in dic){
Debug.Log(item.Key + " : " +item.Value.ToString());
}
saveNameTxt.text = snapshot.GetValue<string>("playerName");
coinsTxt.text = snapshot.GetValue<int>("playerCoin").ToString();
List<string> inventoryList = snapshot.GetValue<List<string>>("playerInventory");
item1Txt.text = inventoryList[0];
item2Txt.text = inventoryList[1];
item3Txt.text = inventoryList[2];
}else{
//show error previous data doesnt exists to load
Debug.Log("No previous data to load");
}
});
}
}
public TMP_InputField registerEmail, registerPassword;
public void RegisterUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.CreateUserWithEmailAndPasswordAsync(registerEmail.text, registerPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = registerEmail.text;
});
}
public TMP_InputField loginEmail, loginPassword;
public void LoginUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInWithEmailAndPasswordAsync(loginEmail.text, loginPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = loginEmail.text;
});
}
void ConnectToFirebase(){
AuthCode=PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("Gplay auth " + AuthCode);
Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Firebase.Auth.Credential FBCred = Firebase.Auth.PlayGamesAuthProvider.GetCredential(AuthCode);
FBAuth.SignInWithCredentialAsync(FBCred).ContinueWithOnMainThread(task => {
if(task.IsCanceled){
firebaseStatText.text = "sign in cancelled";
}
if(task.IsFaulted){
firebaseStatText.text = "Error:"+task.Result;
}
Firebase.Auth.FirebaseUser user = FBAuth.CurrentUser;
if(user != null){
// userID = user.UserId;
// firebaseStatText.text = "Signed in As :"+ user.DisplayName;
// IsConnected = true;
OnAuthSuccess(user);
userNameCloud = user.DisplayName;
}
else{
//error getting username
}
});
// PlayGamesPlatform.Instance.RequestServerSideAccess(true , code => {
// AuthCode = code;
// Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
@@ -79,4 +234,11 @@ public class gplayAuth : MonoBehaviour{
// });
}
public void OnAuthSuccess(Firebase.Auth.FirebaseUser user){
userID = user.UserId;
firebaseStatText.text = "Signed in As :"+ user.DisplayName;
IsConnected = true;
//load game scene
SceneManager.LoadScene("MenuScene");
}
}

19
Assets/startClient.cs Normal file
View File

@@ -0,0 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class startClient : MonoBehaviour
{
public NetworkManager networkManager;
void Start()
{
networkManager.StartClient();
}
// Update is called once per frame
void Update()
{
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d3a46f3965e4c4fca9282d03e7c4ecf9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: