当玩家向前移动时,将实例化GameObject绘制并将其存储在数组中,即使对象绘制已经在数组中。
如何阻止对象绘画多次存储在数组中?
public GameObject[] array;
public GameObject paint;
int temp = 0;
private RaycastHit hit;
public float speed = 10f;
public Text levelText;
public GameObject paint;
float maxdistance = 0.51f;
Vector3 newtargetposition;
bool pos;
private void FixedUpdate()
{
if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forw ard,out hit, maxdistance))
{
if (hit.collider.gameObject.tag == "Obstacle")
{
move = false;
}
if (move)
{
PlayerMove();
}
}
}
public void PlayerMove()
{
if (move)
{
vector3 positions = transform.position + new Vector3(0f, -0.5f,0f); //when player move then paint instantiate y position
array[temp] = Instantiate<GameObject>(paint, position, Quaternion.identity);
temp++;
newtargetposition=position;
Debug.Log("newtargetposiiton:" + newtargetposition);
if (temp == 150)
{
if (newtargetposition == position)
{
//what can i do here
//i dont want to paint here because position store in newtargetposition,it is repeat
//array[temp]--;
Debug.Log("newtargetpositions:" + newtargetposition);
//temp--;
}
gameOver.SetActive(true);
SceneManager.LoadScene(1);
}
}
}
如何删除对象的重复实例化和数组中的重复对象?
答案 0 :(得分:0)
尽管我知道循环效率很低,但我认为这将是您的处理方式,到目前为止,这可能是处理问题的最佳方法
if (move)
{
//boolean is created to return if paint is in the array
bool blnUnique = true;
foreach (GameObject temp in array)
{
if (temp == paint)
{
blnUnique = false;
}
}
if (blnUnique)
{
vector3 positions = transform.position + new Vector3(0f, -0.5f, 0f); //when player move then paint instantiate y position
array[temp] = Instantiate<GameObject>(paint, position, Quaternion.identity);
temp++;
newtargetposition = position;
Debug.Log("newtargetposiiton:" + newtargetposition);
if (temp == 150)
{
if (newtargetposition == position)
{
//what can i do here
//i dont want to paint here because position store in newtargetposition,it is repeat
//array[temp]--;
Debug.Log("newtargetpositions:" + newtargetposition);
//temp--;
}
gameOver.SetActive(true);
SceneManager.LoadScene(1);
}
}
}
并删除所有重复的值
private void CleanArray(ref GameObject[] array)
{
GameObject[] goTemp = new GameObject[0];
bool blnFirst = true;
bool blnTracker = false;
foreach (GameObject V in array)
{
//This is to make sure that there is some value in temp to test against
if (blnFirst)
{
Array.Resize(ref goTemp, goTemp.Length + 1);
goTemp[goTemp.Length - 1] = V;
blnFirst = false;
}
blnTracker = true;
foreach (GameObject T in Temp)
{
if (T == V)
{
blnTracker = false;
break;
}
}
if(blnTracker)
{
Array.Resize(ref goTemp, goTemp.Length + 1);
goTemp[goTemp.Length - 1] = V;
}
}
array = goTemp;
}
这将是我个人的处理方式,但是我通常不使用unity和gameobject,因此它可能无法按预期工作,但是remove函数和catch都适用于整数和较小,较不复杂的数据类型。