- Home /
The question is answered, right answer was accepted
Why this C# Code doesnt works? Raycast problems..
tbh i really tried to figure it out but come on, do you see any mistake here? xd
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwitchCamera : MonoBehaviour
{
public KeyCode keycode;
public Camera camera1;
public Camera camera2;
public float range;
public void Update()
{
if (Input.GetKeyDown(keycode))
{
RaycastHit hit;
if (Physics.Raycast(camera1.transform.position, camera1.transform.forward, out hit, range))
{
if (hit.transform.name == "PC")
{
camera1.enabled = !camera1.enabled;
camera2.enabled = !camera2.enabled;
}
}
}
}
}
Everything looks fine to me. Does the "PC" object have a non trigger Collider?
Try adding Debug.Log()
within each if statement to make sure you catch everything. You can also use Debug.DrawLine (camera1.transform.position, hit.point, Color.yellow, 1f);
to see where the Raycast and hit is happening.
Also, we often use Get$$anonymous$$eyUp rather than Get$$anonymous$$eyDown as most events happen when you release a key.
Answer by black_sheep · Oct 24, 2018 at 12:57 AM
Doesn't seem to have anything wrong with it. My guess it's you didn't set things right in the inspector.
All those variables will have a default value of null (except for range, which will be 0). You either didn't set them at all in the inspector or are settings them the wrong way through another script (given the variables are public)
I remember there was this time where i was changing the keycode to a wrong value every now and than. The script was doing what it was told to do, i was the one to give it a wrong use
I did everything you said in Inspector before i post it. Now I found a solution. Idk why when i was setting "$$anonymous$$ainCamera" as camera1 and "2ndCamera" as camera2 it was a problem and it didnt work, but when i switch that its ok. kek
Follow this Question
Related Questions
Layer and LayerMask Variables 0 Answers
Raycast Target select a multiple objects 1 Answer
How do i get the Raycast rotation? 1 Answer
Multiple Cars not working 1 Answer