我試圖創建一個精靈條。我創建了一個遊戲對象列表,它似乎工作正常。除了我在遊戲視圖中有一個重複的對象,所以好像我需要銷燬我的「模板對象」。當我這樣做的時候看起來很好,但是當我嘗試移動它時,它說我試圖訪問一個已被銷燬的對象。有人可以幫助解釋我的問題嗎?看起來我很困惑實例化以及它是如何工作的。我的印象是,在實例化之前,對象不是在遊戲視圖中創建的。但那爲什麼我會得到一個重複的對象?感謝您的輸入。創建一個Unity對象列表
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ReelStrip : MonoBehaviour {
public List <Sprite> image = new List<Sprite>();
public List <int> index = new List<int>();
public List <GameObject> symbol = new List<GameObject>();
public int reelNumber;
public float symbolHeight = 1.74f;
public float symbolWidth = 2.00f;
public float speed = 0.01f;
// Use this for initialization
void Start() {
reelNumber = 0;
loadStrip (new List<int>{0,0,1,2,4,1,4,5});
}
void addSymbol(int indexToAdd)
{
string name = "reelNum: " + reelNumber + " index " + indexToAdd;
SpriteRenderer renderer = new SpriteRenderer();
GameObject symbolObject = new GameObject (name);
symbolObject.AddComponent<SpriteRenderer>();
renderer = symbolObject.GetComponent<SpriteRenderer>();
symbolObject.AddComponent<symbol>();
Sprite loadedSprite = Resources.Load <Sprite>(symbolNameAtIndex(indexToAdd)) as Sprite;
renderer.sprite = loadedSprite;
symbol.Add (symbolObject);
Vector3 newPos;
if(symbol.Count<2)
{
newPos = new Vector3(0.0f,0.0f,0.0f);
}
else{
newPos = new Vector3(symbol[symbol.Count-1].transform.position.x,symbol[symbol.Count-1].transform.position.y + symbolHeight, 0.0f);
}
Instantiate (symbol[symbol.Count-1], newPos, Quaternion.identity);
// destroy template object
///// confused on the destroy //////
//Destroy (symbolObject);
}
public void moveStripDown(float delta)
{
for (int i=0;i<symbol.Count;i++)
{
symbol[i].transform.position = new Vector3(symbol[i].transform.position.x,symbol[i].transform.position.y - delta, symbol[i].transform.position.z);
}
}
public void loadStrip(List <int> Indexes)
{
for (int i=0;i<Indexes.Count;i++)
{
addSymbol (Indexes[i]);
}
}
public string symbolNameAtIndex(int index)
{
string returnString;
switch (index) {
case 0:
returnString = "img1";
break;
case 1:
returnString = "img2";
break;
case 2:
returnString = "img3";
break;
case 3:
returnString = "img4";
break;
case 4:
returnString = "img5";
break;
default:
returnString = "symbolnotfound";
break;
}
return returnString;
}
// Update is called once per frame
void Update() {
moveStripDown (speed*Time.deltaTime);
}
}
如果我跳過實例化如何我輕鬆地引用符號?這是名單的目的?我原本在那裏銷燬。銷燬(symbolObject),但是當它試圖加載moveStripDown函數時它會說「gameObject已經被銷燬,但你仍然試圖訪問它。」 –
好的,我現在明白了。它看起來像symbol.Add(symbolObject)是我所需要的。我仍然可以很容易地引用它們。我刪除了實例化。謝謝。 –
沒問題,很高興有人幫忙! –