Can Anyone help me with Raycasting?
Why do I get this error?
UnityEngine.Component' does not contain a definition for ScreenPointToRay' and no extension method
ScreenPointToRay' of type `UnityEngine.Component' could be found. Are you missing an assembly reference?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowPortal : $$anonymous$$onoBehaviour {
public GameObject LeftPortal;
public GameObject RightPortal;
public GameObject mainCamera;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.Get$$anonymous$$ouseButton (0)) {
Debug.Log ("Left Click");
throwPortal (LeftPortal);
}
if (Input.Get$$anonymous$$ouseButton (1)) {
Debug.Log("Right Click");
throwPortal (RightPortal);
}
}
void throwPortal(GameObject portal){
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = camera.ScreenPointToRay(new Vector3 (x, y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
portal.transform.position = hit.point;
}
}
}
Answer by tanoshimi · Feb 04, 2017 at 08:15 AM
The error tells you that ScreenPointToRay is a method of the camera class, not of a generic Unity component.
Your code is a bit confusing, because you declare a mainCamera gameobject which you never use, and call ScreenPointToRay on a camera variable that you never define.
Try this instead:
Ray ray = Camera.main.ScreenPointToRay(new Vector3 (x, y));
https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
Your answer
Follow this Question
Related Questions
Raycasting through UI Image with transparent part 5 Answers
Select from multiple character to move 0 Answers
Ray-casting Problem 0 Answers
Raycast positioning problem 1 Answer
NullReferenceException on Raycast 0 Answers