- Home /
What is going on with my for loop?
I have seen dozens of issues regarding for loops here, but the scenarios don't really seem to match my issue. A lot just seem like people putting for loops in the update function. Anyways, I'm trying to set this up so that when you enter a trigger, it spawns two monsters, one at each spawn point. I can get the "Entered the Trigger" message to come up, but I don't get the "Spawn Monster" + i to show up. I expect this is really easy to fix, but I'm just out of ideas.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class WesternCottageTrigger : MonoBehaviour {
public GameObject[] spawnPoints;
private GameObject currentPoint;
public GameObject monster;
private int index;
void Start()
{
Debug.Log(spawnPoints.Length);
spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint");
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Entered the Trigger");
for (int i = 0; i < spawnPoints.Length; i++)
{
Debug.Log("Spawn Monster " + i);
currentPoint = spawnPoints[i];
monster = Instantiate(monster, currentPoint.transform.position, currentPoint.transform.rotation) as GameObject;
}
}
}
Below is also what I have setup in Inspector for spawnPoints and Monster
Answer by Yuvii · Oct 09, 2017 at 12:37 PM
If you don't get the '"Spawn Monster" + i ' then i guess it doesn't enter in the loop. Try to see if the spawnPoints.Length is superior to 0 with
Debug.Log(spawnPoints.Length);
just before the loop. I see in the Start that you look at his lenght, then you define him (the other way would work better i think)
Ok. That does answer why it is not entering the loop. Thank you. Now I have to figure out why the length is switching back to 0.
EDIT: I actually just figured it out. Got rid of spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint"); and it works perfectly now. Thank you again for the push past the mental block.
You're right that they should be checking the size of the array after using Find rather than before.
But, since they've set up the spawnPoints as an array in the inspector, they shouldn't need to use Find at all.
I suspect that that redundant Find call in Start() is finding nothing and so clearing the array that's been set up in the inspector (and so the Find line should be deleted).
Your answer

Follow this Question
Related Questions
Space Shooter Tutorial 5.3 first Asteroid being destroyed 0 Answers
Help with VR Controller Collider 1 Answer
How to Get Next One On The Que? 0 Answers
Guides or Tutorials for a Very Basic Enemy AI? [Unity 5] 1 Answer
How do I pass a parameter for trigger animations in the animator controller unity 5 file 0 Answers