【发布时间】:2017-02-02 08:53:12
【问题描述】:
我想在 20 个随机位置列表中的 3 个位置实例化 3 个游戏对象。当我玩游戏时,它会在 20 个位置实例化 20 个游戏对象,而不是 3 个游戏对象。我该怎么做?这是我的代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnManager: MonoBehaviour {
private GameObject Player;
public List<GameObject> spawnPositions;
public List<GameObject> spawnObjects;
void Start()
{
Player = GameObject.FindGameObjectWithTag("Player");
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
SpawnObjects ();
}
}
void SpawnObjects()
{
foreach (GameObject spawnPosition in spawnPositions)
{
int selection = Random.Range (0, spawnObjects.Count);
Instantiate (spawnObjects [selection], spawnPosition.transform.position, spawnPosition.transform.rotation);
}
}
}
更新:
有时 2 个对象被放置在同一个位置,我希望这些对象在不同的位置实例化。我尝试将随机位置添加到列表中,并且仅在它不在列表中时才实例化,但它不起作用。这是我的代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnManager : MonoBehaviour {
private GameObject Player;
public List<GameObject> spawnPositions;
public List<GameObject> spawnObjects;
private GameObject obj;
void Start()
{
Player = GameObject.FindGameObjectWithTag("Player");
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
SpawnObjects ();
}
}
void SpawnObjects()
{
for (int i = 0; i < 3; ++i)
{
int randomObject = Random.Range(0, spawnObjects.Count);
int randomPosition = Random.Range(0, spawnPositions.Count);
List <GameObject> _spawnPositions = new List<GameObject>();
obj = spawnPositions[randomPosition];
_spawnPositions.Add(obj);
if (!_spawnPositions.Contains (obj))
{
Instantiate (spawnObjects [randomObject], _spawnPositions [randomPosition].transform.position, _spawnPositions [randomPosition].transform.rotation);
}
else
{
Debug.Log ("error");
}
}
}
}
【问题讨论】:
-
你正在循环所有位置并向它们添加随机对象,你也需要随机化。
-
int rnd = /*random integer*/; foreach(var spawnPoint in spawnPositions.OrderBy(g => rnd).Take(3)) { /*your instantiate code*/ }