Debugging Collision script - Help required to understand behaviour
Hi All.
This is my 1st post so if I use some wrong terms please be patient with me.
I have a simple 3d scene where cubes fall from a spawning location. The cubes can be moved left or right as they fall. There is a Plane underneath the falling cube. When the cube collides with the plane it's movement is stopped and a new cube is spawned. This works perfectly UNTIL a cube falls onto an existing cube, when suddenly the spawner triggers continuously. The spawner script is:
using UnityEngine;
using System.Collections;
public class scr_Spawner : MonoBehaviour {
// Use this for initialization
void Start () {
// Spawn initial Group
spawnNext();
}
// Groups
public GameObject note;
public void spawnNext() {
Instantiate(note, transform.position, Quaternion.identity);
}
}
And the collider script is:
using UnityEngine;
using System.Collections;
public class scr_Note_Collider : MonoBehaviour {
void OnCollisionEnter(Collision col)
{
enabled = false;
GetComponent<scr_Note_Controller>().enabled = false;
FindObjectOfType<scr_Spawner> ().spawnNext ();
}
}
Is there something obviously wrong here or is more information needed?
All help gratefully received.
Not sure if this would fix it but I'd imagine you'd want to disable the scripts AFTER line 10 either way, try that and see if it has an effect?
Answer by Matt-Face · Mar 04, 2016 at 03:38 PM
OnCollisionEnter will get called for every new collision. you might want to experiment with OnCollisionStay OR depending on your requirements, you may want to use a bool to check if it has fired yet, so that it only fires on the first collision.
using UnityEngine;
using System.Collections;
public class scr_Note_Collider : MonoBehaviour
{
private bool fired = false;
void OnCollisionEnter(Collision col)
{
if(!fired)
{
enabled = false;
//GetComponent<scr_Note_Controller>().enabled = false;
FindObjectOfType<scr_Spawner> ().spawnNext ();
fired = true;
}
}
}
Answer by Des6314 · Mar 09, 2016 at 07:33 AM
Hi @Grin - Sorry for the slow reply and thanks very much for the answer it worked perfectly! Now I just need to understand why :-/
Also, was there a reason that you rem'd out the GetComponent<scr_Note_Controller>().enabled = false;
line?
Many thanks again!
Your answer
Follow this Question
Related Questions
How do I make player attack with LMB if the enemy is within range? 0 Answers
How to trigger a BoxCollider with a RigidBody? 0 Answers
Switch Scene on Collision with a Box 1 Answer
How can i restart a script on collision ? 1 Answer
[emergency]Know collision between child object of two object 1 Answer