I’m currently making a script that allows a object to be destroyed on trigger, and it works fine, but when I make the object re spawn the the on trigger enter does not work? It’s a 2D game and I’ve mad similar scripts for 3D game with success, but for some reason the script seem not to work in 2D? and yes I did OnTriggerEnter2D ( Collider2D info ). I feel like it might have to do with layers, but Idk 100%. any ideas?
It works on the one in the scene, but not when spawned from a prefab, is that right? Maybe there’s some setting or component on the in-scene one that hasn’t been applied back to the prefab?
“t works on the one in the scene, but not when spawned from a prefab, is that right?” yes that is correct. but “Maybe there’s some setting or component on the in-scene one that hasn’t been applied back to the prefab?” I thought of that solution, so i dragged the prefab onto the scene and I could collect it like the regular object, but again. after I collect it and a new one spawns the newly spawned object I cant collect…
That’s really strange. Is the other object (the one that collects these objects) doing some initialization where it finds all the objects available in the start of the scene?
Also, is there anything in the console?
Nope, the player has no scripts attached that allows him to “find all the objects available in the start” it’s just a simple “OnTriggerEnter” script. attached to the prefab like so: (not all of code but most. the rest is irrelevant )
void OnTriggerEnter2D ( Collider2D info ){
if (info.name == "Player")
{
Debug.Log ("Hitting");
Num = Num+1;
Score.score += +1;
FinalScore.score1 +=+1;
Destroy(gameObject);
as for the spawning script:
void OnTriggerEnter2D (Collider2D info)
{
if (info.name == "Player")
{
SpawnCoin();
}
}
void SpawnCoin()
{
Vector3 position = new Vector3(Random.Range(-9f, 9F), Random.Range(-5.56F, 5.27F), 0);
Instantiate (prefab, position, Quaternion.identity);
}
I think I found the problem. For some reason beyond my knowledge the object spawns with all attached scripts on it, but the scripts are disabled?? (including Colliders )
Put some Debug.Log’s in OnTriggerEnter2D - one inside, and one outside that ‘if’ statement. Check to see if it’s calling the trigger enter function, and if that if statement is just starting to return false.
That shouldn’t happen, as far as I know. Can you paste the code where the new thing gets spawned?
using UnityEngine;
using System.Collections;
public class random : MonoBehaviour
{
public GameObject prefab;
void OnTriggerEnter2D (Collider2D info)
{
if (info.name == "Player")
{
SpawnCoin();
}
}
void SpawnCoin()
{
Vector3 position = new Vector3(Random.Range(-9f, 9F), Random.Range(-5.56F, 5.27F), 0);
Instantiate (prefab, position, Quaternion.identity);
}
}
exact coding of re spawning object