- Home /
JavaScript collision code problem.
This very simple piece of code is supposed to change levels when the game object it's attached to hits a specific game object. The problem is when the two objects collide the scene doesn't change. Here is the code:
#pragma strict
function OnCollisionEnter(CrystalCollision : Collision){
if(CrystalCollision.gameObject.name == "Crystal"){
Application.LoadLevel(0);
}
}
-Thanks
Two things I'd check, up front:
Is LoadLevel being called in the first place? You could stick a simple
Debug.Log("Here")
right next to it, just to be sure.Do you have any levels set up in your build settings? LoadLevel only works with those levels.
I'm hesitant to let this through the moderation queue because it's a frequently asked question. It's not a bad question, we're just trying to cut down on the number of duplicate threads in this area of the site. If you have anything else to add, feel free to comment here; if not, I'll drop the question from the queue in a little while.
If you can't find help, here, you can always try the forums or look up some tutorials online.
You haven't provided enough information really to solve this issue. As rutter said, you should check if the collision even calls Application.LoadLevel() by dropping a Debug.Log statement.
However, you could be overlooking the fact that if you are making a 2D game, you need to use the 2D variation of OnCollisionEnter.
I don't know if you're making 2D, because you didn't include that information, but it's a fairly common problem. If nothing said so far fixes/identifies the problem, post back more information.
Ok so I's using 3D(sorry for not including that info) and I replaced the LoadLevel with Debug.log to see if it's being called and it's not :/ Edit: I accidentally on my rig body turned on "is kinematic"
I fixed it :/
Is the OnCollisionEnter being called? $$anonymous$$ore Debug.Log:
#pragma strict
function OnCollisionEnter(CrystalCollision : Collision){
Debug.Log("OnCollisionEnter invoked");
Debug.Log("Collided with game object named: " + CrystalCollision.gameObject.name);
if(CrystalCollision.gameObject.name == "Crystal"){
Debug.Log("Loading Level");
Application.LoadLevel(0);
}
}
Answer by aress · Aug 21, 2014 at 02:16 PM
Try to use CrystalCollision.gameObject.name.Equals("Crystal") to compare the string
Your answer
![](https://koobas.hobune.stream/wayback/20220613161134im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Camera Follow 1 Answer