如何使用C#访问另一个类(在unity3d中)
本文关键字:unity3d 何使用 访问 另一个 | 更新日期: 2023-09-27 18:28:44
这是我的问题:我在c#中有一个播放器类和SwipeDetector类,SwipeDetective类有助于在iPhone上进行识别的垂直滑动触摸。
p.s.我使用的是unity3d,但这是一个与游戏技术相反的编程问题:)
在我的玩家类中,我试图访问SwipeDetector,并找出它是哪一次滑动(向上、向下)。
player.cs:
if(SwipeDetetcor is up){
print("up");
}
这是SwipeDetector类,它看起来很可怕,但事实并非如此!!
using UnityEngine;
using System.Collections;
public class SwipeDetector : MonoBehaviour {
// Values to set:
public float comfortZone = 70.0f;
public float minSwipeDist = 14.0f;
public float maxSwipeTime = 0.5f;
private float startTime;
private Vector2 startPos;
private bool couldBeSwipe;
public enum SwipeDirection {
None,
Up,
Down
}
public SwipeDirection lastSwipe = SwipeDetector.SwipeDirection.None;
public float lastSwipeTime;
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
switch (touch.phase)
{
case TouchPhase.Began:
lastSwipe = SwipeDetector.SwipeDirection.None;
lastSwipeTime = 0;
couldBeSwipe = true;
startPos = touch.position;
startTime = Time.time;
break;
case TouchPhase.Moved:
if (Mathf.Abs(touch.position.x - startPos.x) > comfortZone)
{
Debug.Log("Not a swipe. Swipe strayed " + (int)Mathf.Abs(touch.position.x - startPos.x) +
"px which is " + (int)(Mathf.Abs(touch.position.x - startPos.x) - comfortZone) +
"px outside the comfort zone.");
couldBeSwipe = false;
}
break;
case TouchPhase.Ended:
if (couldBeSwipe)
{
float swipeTime = Time.time - startTime;
float swipeDist = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude;
if ((swipeTime < maxSwipeTime) && (swipeDist > minSwipeDist))
{
// It's a swiiiiiiiiiiiipe!
float swipeValue = Mathf.Sign(touch.position.y - startPos.y);
// If the swipe direction is positive, it was an upward swipe.
// If the swipe direction is negative, it was a downward swipe.
if (swipeValue > 0){
lastSwipe = SwipeDetector.SwipeDirection.Up;
print("UPUPUP");
}
else if (swipeValue < 0)
lastSwipe = SwipeDetector.SwipeDirection.Down;
// Set the time the last swipe occured, useful for other scripts to check:
lastSwipeTime = Time.time;
Debug.Log("Found a swipe! Direction: " + lastSwipe);
}
}
break;
}
}
}
}
如果您想从播放器类访问SwipeDetector
,只需使用一个公共变量即可。
// Player.cs
public SwipeDetector MySwipeDetector;
void Update()
{
if (MySwipeDetector.lastSwipe == SwipeDirection.Up) { .... }
}
如果不想将公共变量设置为统一,可以使用一种singletone模式。
// SwipeDetector.cs
private static SwipeDetector _Instance;
public static SwipeDetector Instance { get { return _Instance; } }
void Awake()
{
if (_Instance!= null) throw new Exception(...);
_Instance= this;
}
并以这种方式使用:
// Player.cs
void Update()
{
if (SwipeDetector.Instance.lastSwipe == SwipeDirection.Up) { .... }
}
向您的Player类添加一个公共变量。
// player.cs
public SwipeDetector swipeDetector;
现在,当您单击玩家游戏对象时,您将在编辑器中看到SwipeDetector变量。将编辑器中有SwipeDetector的空gameObject分配给它。现在你可以访问该类了。
// you can now use it like this:
if(swipeDetector.lastSwipe == SwipeDetector.SwipeDirection.UP)
{
// do something
}