[英]How to create a winning condition when a certain number of game objects have spawned
我正在嘗試讓我的 3-D Tic-Tac-Toe 游戲項目運行,我有游戲對象,這些對象被命名為實例化的單元格我按下 OnMouseDown() 單擊它會在其網格空間中生成一個單元格 object。 我不想將 UI 與我創建的基本預制件一起使用。 有沒有辦法讓我的游戲對象實例化,一旦達到一定數量作為獲勝條件? 我考慮過使用尋路,但我不確定這是否是正確的方法。 我到處尋找適合我的問題的解決方案,但找不到解決方案。 也許,我問錯了問題,但我很絕望,所以我來找她,看看我是否可以就如何解決這個問題征求意見。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
public class Cell : MonoBehaviour
{
public GameObject cell;
public GameObject negCell;
public GameObject alter;
public Transform transPos;
[SerializeField]
private bool isTapped = false;
private int counted;
public int gameObjectCount;
void Start()
{
gameObjectCount = GameObject.FindGameObjectsWithTag("Cell1").Length;
}
void Update()
{
}
public void OnMouseDown(int counted) //click and point to create and deestroy objects
{
counted = gameObjectCount;
isTapped = true;
transPos = alter.transform;
Instantiate(cell, transform.position, Quaternion.identity);
StartCoroutine(WaitForObject());
Debug.Log("Alter Destroyed!");
gameObjectCount++;
DestroyGameObject();
return;
}
IEnumerator WaitForObject()
{
if (isTapped == true)
{
Instantiate(negCell, -transform.position, Quaternion.identity);
isTapped = false;
}
yield return new WaitForSeconds(3f);
DestroyGameObject();
}
void DestroyGameObject()
{
if(gameObject == alter)
{
DestroyImmediate(alter, true);
}
else
{
DestroyImmediate(cell, true);
}
}
}
有兩種簡單的方法可以實現這一點。
第一個是在您的 class 中添加一個 static 成員,假設:
private static int _instanceCounter = 0;
這將充當 class 實例計數器。
您所要做的就是在每次實例化新游戲 object 時遞增此變量。最后,根據您想要的 class 的實例數來確定您的獲勝條件。
如果出於某種原因您在特定游戲 object 上調用 Destroy 方法,您也可以遞減此變量。
另一種方法是使用 Unity 中的FindObjectsOfType方法,該方法返回當前場景中所有實例的數組。 通過訪問此數組的長度,您將獲得實例數。
但是,這只計算調用此方法時的當前實例數。 請注意,您還可以包括場景中的非活動游戲對象(那些在層次結構面板中顯示為灰色的對象)。
您現在有兩種方法可以做到這一點,具體取決於您希望如何實現獲勝條件,即在給定時間實例化的游戲對象總數或特定數量的游戲對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.