- Home /
Camera switching : C# onTriggerEnter not working
Hello. I'm actually making a game in which there are many cameras, and the switch between them occurs when the player enters a specific trigger. In the actual level I'm working on, I have 9 different cameras.
At first, I did it with Javascript, with the following code :
var cam1 : Camera;
var cam2 : Camera;
function Start() {
cam1.enabled = true;
cam2.enabled = false;
}
function OnTriggerEnter (player : Collider) {
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;
}
It worked perfectly until the gestion of the cameras went wrong. It either chose the wrong one to start, or failed to switch to a camera, even though it worked before. I assumed it was due to Javascript's instability.I then decided to switch to C# and used this code :
public Camera cam1;
public Camera cam2;
// Use this for initialization
void Start () {
cam1.enabled = true;
cam2.enabled = false;
}
// Update is called once per frame
void Update () {
}
void onTriggerEnter (Collider other) {
if(other.gameObject.tag.Equals("Player")) {
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;
Debug.Log("pass");
}
}
}
Which fails. The trigger detection doesn't work at all, since the Debug.Log doesn't. My player has a capsule Collider and a a Rigidbody component. The trigger box has a collider set to "Trigger". I'm kind of lost since I really don't know what to do anymore. I searched through answer.unity3d for hours now but can't find a proper solution.
Thanks for your help !
Answer by Roland1234 · Nov 26, 2013 at 07:02 PM
Can't speak to the Javascript code, but I can tell you that in the C# version your method should be OnTriggerEnter with a capital O. Unity won't call it spelled otherwise.
In the future I'd advise you to add your Debug.Log calls exactly where you want them - currently you couldn't properly say that the trigger method wasn't even being invoked since it might very well have been, but your other GameObject might not have been tagged "Player" or some operation you were performing before outputting the log might have caused an exception and prevented its execution, etc.
Regarding your specific issue: Well - like I kinda mentioned, make sure that your other object is actually tagged as "Player" and that its Collider and Rigidbody components are actually active. Verify the object with the Collider trigger is also active and that your camera references are setup correctly in the inspector as well. If that doesn't help you might need to include more details of your scene and setup.
Your answer
Follow this Question
Related Questions
Switching Cameras - Confusion with Two Code Samples 2 Answers
Switching cameras (JavaScript) 0 Answers
Check for collision while animating 0 Answers
Multiple Cars not working 1 Answer
switching cameras C# 4 Answers