簡體   English   中英

我可以在 Unity 中創建一個指向 GameObject 的指針嗎?

[英]Can I make a pointer to a GameObject in Unity?

我在 Unity 中制作紙牌游戲類型的東西,因此有一個中央“甲板”,我需要手 class 能夠訪問和繪制,但我似乎無法指向 GameObject,或 GameObject 中的牌組。 理想情況下,抽出的牌應該從中央牌組中取出並移入手中,但手牌卻擁有自己的牌組副本。 這是我嘗試獲取指向 GameObject 的指針的代碼,我也在 DeckHolder 腳本中對卡組進行了同樣的嘗試,但也無濟於事。

`GameObject* holder = &GameObject.Find("obj_tempDeckHolder");`

你不必在 c# 中使用指針。

TL;DR 是的1但您可能不需要指針2

1 Unity 使用 C#。 As opposed to compiled languages like C and C++ C# is a managed language that adds a layer between the code you write and the binary code, which layer "manages" potentially unsafe features like accessing unintended memory through indexing an array out of its bounds, or通過分配 memory 而不是釋放它來創建 memory 泄漏。 這兩個例子都暗示了指針的使用。
所以 C#通常不會讓你使用指針,除非你真的需要它們(並且知道你在做什么),在這種情況下,無論你在哪里聲明和引用像 fi 這樣的指針,你都會創建一個“不安全的上下文”:

public unsafe struct Point2D
{
    public int* x;
    public int* y;
}

甚至:

public struct Point2D
{
    public unsafe int* x;
    public unsafe int* y;
}

Unity 通過 Project Settings > Player 中的“Allow 'unsafe' Code”設置支持這一點。

2即使您使用指針,我也看不出它會如何自動從中心牌組中取出卡片並將其添加到手牌中。
一種快速的方法是讓中央牌組成為HashSet<GameObject>以確保不存在重復的卡片。 如果您確實想要重復,那么List<GameObject>是最合適的。 所以fi

//using System.Collections.Generic;
HashSet<GameObject> centralDeck = new HashSet<GameObject>(); 

每只手(玩家)也將是/有一個HashSetList
為簡單起見,讓我們看看如何使用現有的centralDeckhand1作為List s。 在繪制前 3 張牌時,您只需在方法中執行以下操作:

  // create references to hold objects to transfer
GameObject[] cardsDrawn = new GameObject[3];
  // actually populate them; 'GameObject' is a reference type so copies are created
  // but they point to the same actual objects
centralDeck.CopyTo(0, cardsDrawn, 0, 3);
  // don't use those references for performance reasons;
  // you know those *are* the same objects
centralDeck.RemoveRange(0, 3);
  // now the go's are not part of centralDeck anymore but they still exist
  // and pointed to by cardsDrawn

  // put them in hand1
hand1.AddRange(cardsDrawn);
  // now when the method returns, the copies will be left to garbage collector  

在這里,我嘗試將代碼壓縮為 4 行而不使用循環,但使用循環它更具可讀性/直接性。
一次使用 1 張卡:

GameObject cardDrawn = centralDeck[0];
centralDeck.Remove(cardDrawn);
hand1.Add(cardDrawn);

你可以把它放在一個for循環中。 請注意,即使在for循環中鍵入centralDeck[0] ,而不是centralDeck[i] ,因為列表在迭代之間會“刷新”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM