//basic door with key spawn mobs when unlocked
public class Door : MonoBehaviour
{
public GameObject[] spawnMob;// Ive only put one game object in the array
public GameObject mobSpawnPoint;
public int requiredKeyCode;
Key key;
private void OnTriggerEnter2D(Collider2D collision)
{
key = collision.GetComponent<Key>();
if(key != null && key.keyCode == requiredKeyCode)
{
key.Use();
float offSet = 0;
foreach (var mob in spawnMob)
{
GameObject spawnedEnermy = Instantiate(mob, mobSpawnPoint.transform.position + Vector3.up * offSet + Vector3.right * offSet, Quaternion.identity);//this spawns 2 of the item?
offSet += Random.Range(-2f, 2f);
}
Destroy(gameObject);
}
}
I mean, running the code multiple times is the point of a loop. Mind explaining your problem more?
So i would like it to spawn 1 of what ever i put in the array but at the moment it spawns 2 of every thing in the array
Time for putting Debug.Log() statements in your code. Your for loop will not do that. What is happening is this OnCollisionEnter2D method is running multiple times. This could be caused by:
- Multiple copies of this script
- Multiple collisions happening (Maybe one of your objects has multiple colliders?)
I have checked all the components and i can verify there are no double of anything
Use Debug.Log and find out how many times is the method running? What are the names/object IDs of the colliders involved?
It runs twice per item in the array
The ENTIRE method runs twice, right? That means there are two collisions happening.
Again, figure out which colliders are involved in each collision. Probably your key is interacting with both colliders on the door or vice-versa.
If i set activate it with on destroy it works fine but id like to keep spawning using it to a minimum
It was the trigger collider for the key making it run twice any suggestion on a work around that allows me to use both triggers?
{
public int keyCode;
Transform player;
public void Use()
{
Destroy(gameObject);
}
private void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag("MagGrab") && Input.GetKey(KeyCode.LeftShift))
{
Debug.Log("This is Key Code " + keyCode);
player = other.transform;
transform.position = Vector2.MoveTowards(transform.position, player.position, 3 * Time.deltaTime);
}
}
Put the different colliders on different GameObjects that are children of the current objects and put them on different layers that don’t interact with one another.
Ok thanks for the help