我正在尝试创建一个文字游戏(代码here)。我希望将单词分配给从屏幕顶部生成并掉到底部的3个敌人。这是敌人的脚本:
public class Enemy : MonoBehaviour {
public float fallSpeed = 1.0f;
void Update () {
transform.Translate(0, -fallSpeed * Time.deltaTime, 0);
}
}
以下是“ spawner”一词:
public class WordSpawner : MonoBehaviour {
public GameObject wordPrefab;
public GameObject enemy;
public Transform wordCanvas;
public WordDisplay SpawnWord()
{
Vector3 randomPosition = new Vector3(UnityEngine.Random.Range(-2.0f, 2.0f), 7.0f, 0);
GameObject wordObj = Instantiate(wordPrefab, randomPosition, Quaternion.identity, wordCanvas);
WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
return wordDisplay;
}
}
这是计时器一词:
public class Wordimer : MonoBehaviour {
public WordManager wordManager;
public float delay = 1.5f;
private float nextWord = 0f;
void Update()
{
if (Time.time >= nextWord)
{
wordManager.AddWord();
nextWord = Time.time + delay;
delay *= 0.95f;
}
}
}
上面脚本中的AddWord()方法是从单词列表中随机生成单词的方法。这是添加单词方法(此方法在单独的文件中):
public void AddWord()
{
WordDisplay wordDisplay = wordSpawner1.SpawnWord();
Word word = new Word(WordGenerator.GetRandomWord(), wordDisplay);
words.Add(word);
}
所以我希望将这些单词与敌人的游戏对象一起生成。现在,它们自己产生。如何实现此功能?
修改
这是产生敌人的脚本:
public GameObject enemy;
public float spawnTime = 3.0f;
public Transform[] spawnPoints;
void Start () {
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Spawn()
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
答案 0 :(得分:0)
如果我正确理解了您的问题,那么您试图归档的内容就是生成WordDisplay
并将其保持在相应enemy
对象的旁边,该对象已经在WordSpawner
中
您可以将其分配给某个Enemy
,让敌人像这样更新位置
public class Enemy : MonoBehaviour
{
public float fallSpeed = 1.0f;
public WordDisplay assosiatedDisplay;
// optional for allways showing the text e.g. 10 cm above enemies
public Vector3 offset = new Vector3(0, 0.1f, 0);
void Update ()
{
transform.Translate(0, -fallSpeed * Time.deltaTime, 0);
if(assosiatedDisplay)
{
// keep the referenced wordDisplay positioned relative to this object
assosiatedDisplay.transform.position = transform.position + offset;
}
}
}
然后在生成associatedDisplay
时设置WordDisplay
值
public class WordSpawner : MonoBehaviour
{
public GameObject wordPrefab;
public GameObject enemy;
public Transform wordCanvas;
public WordDisplay SpawnWord()
{
GameObject wordObj = Instantiate(wordPrefab, enemy.transform.position * new Vector3(1, 1, 0), Quaternion.identity, wordCanvas);
WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
// assign it to the enemy
enemy.GetComponent<Enemy>().assosiatedDisplay = wordDisplay;
return wordDisplay;
}
}
更新
我在您的问题中看不到,也不知道在哪里调用所有方法。
但是,当实例化敌人对象时,您将以相同的方式存储enemy
引用:
var enemy = Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
,然后将该enemy
引用传递给public WordDisplay SpawnWord()
,例如
public WordDisplay SpawnWord(Enemy enemy)
{
// ...
// assign it to the enemy
enemy.assosiatedDisplay = wordDisplay;
}