I'm trying to create a falling word game (code here). I want the words to be assigned to 3 enemies that spawn from the top of the screen and fall down to the bottom. Here is the enemy script:
public class Enemy : MonoBehaviour {
public float fallSpeed = 1.0f;
void Update () {
transform.Translate(0, -fallSpeed * Time.deltaTime, 0);
}
}
Here is the word 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;
}
}
This is the word timer:
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;
}
}
}
The AddWord() method in the above script is what generates the word randomly from a list of words. Here is the add word method (this method is in a separate file):
public void AddWord()
{
WordDisplay wordDisplay = wordSpawner1.SpawnWord();
Word word = new Word(WordGenerator.GetRandomWord(), wordDisplay);
words.Add(word);
}
So what I would like for the words to be spawned along with the enemy game objects. Right now they spawn on their own. How can I achieve this functionality?
Edit
This is the script that spawns the enemy:
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);
}
If I understand your question correctly what you are trying to achieve is spawning the
WordDisplay
and keep it "next to" the accordingenemy
object, the reference you already have inWordSpawner
.You could assign it to a certain
Enemy
and let the enemy update the position likeAnd than set that
associatedDisplay
value when you spawn theWordDisplay
Update
I don't see in your question and have no clue where all your methods are called. But you would store the according
enemy
reference the same way when you instantiate your enemy objects:and later pass that
enemy
reference to thepublic WordDisplay SpawnWord()
e.g.