我真的不确定这是错的......
我正在关注YouTube视频,因为这段代码对我来说太先进了。我不知道它是否与unity 5或者其他什么问题,但它只是一直给我这个错误:错误CS0120:需要一个对象引用来访问非静态成员`UnityEngine.Camera.ScreenPointToRay(UnityEngine.Vector3)'
我知道从YouTube上复制而不知道它意味着什么可能是一个坏主意,但我只想尝试获取触摸屏内容的脚本。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TouchInput : MonoBehaviour {
public LayerMask touchInputMask;
private List<GameObject> touchList = new List<GameObject>();
private GameObject[] touchesOld;
private RaycastHit hit;
void Update () {
#if UNITY_EDITOR
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) {
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit,touchInputMask)){
GameObject recipient = hit.transform.gameObject;
touchList.Add(recipient);
if(Input.GetMouseButtonDown(0)){
recipient.SendMessage("OnTouchDown",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(Input.GetMouseButtonUp(0)){
recipient.SendMessage("OnTouchUp",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(Input.GetMouseButton(0)){
recipient.SendMessage("OnTouchStay",hit.point,SendMessageOptions.DontRequireReceiver);
}
}
foreach (GameObject g in touchesOld){
if(!touchList.Contains(g)){
g.SendMessage("OnTouchExit",hit.point,SendMessageOptions.DontRequireReceiver);
}
}
}
#endif
if (Input.touchCount > 0) {
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
foreach (Touch touch in Input.touches) {
Ray ray = Camera.ScreenPointToRay(touch.position);
if(Physics.Raycast(ray,out hit,touchInputMask)){
GameObject recipient = hit.transform.gameObject;
touchList.Add(recipient);
if(touch.phase == TouchPhase.Began){
recipient.SendMessage("OnTouchDown",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Ended){
recipient.SendMessage("OnTouchUp",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved){
recipient.SendMessage("OnTouchStay",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Canceled){
recipient.SendMessage("OnTouchExit",hit.point,SendMessageOptions.DontRequireReceiver);
}
}
}
foreach (GameObject g in touchesOld){
if(!touchList.Contains(g)){
g.SendMessage("OnTouchExit",hit.point,SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
答案 0 :(得分:3)
我不是Unity专家,但文档说ScreenPointToRay是一个实例方法,而不是静态方法。这意味着您必须在使用之前创建Camera实例。所以,也许:
camera = GetComponent<Camera>();
Ray ray = camera.ScreenPointToRay(touch.position);
请注意,您的代码段中有两处您需要进行此更改。