访问名称空间中的类中的float浮点数
我试图在下面的脚本中从另一个脚本更改'XSensitivity'的值。访问名称空间中的类中的float浮点数
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[Serializable]
public class HeadLook
{
public float XSensitivity = 8f;
public float YSensitivity = 8f;
public float MinimumX = -60F;
public float MaximumX = 60F;
public float xRotRaw;
public float yRotRaw;
public HeadLook (float rotX, float rotY)
{
rotX = XSensitivity;
rotY = YSensitivity;
}
// create an instance (an Object) of the HeadLook class
public HeadLook MyHeadLook = new HeadLook(8,8);
private float xRot;
private float yRot;
private float xRotation;
private float yRotation;
// ----------------------------
public void LookRotation(Transform character, Transform head)
{
yRotRaw = CrossPlatformInputManager.GetAxisRaw("HorizontalLook");
xRotRaw = CrossPlatformInputManager.GetAxisRaw("VerticalLook");
yRot = CrossPlatformInputManager.GetAxisRaw("HorizontalLook") * XSensitivity;
xRot = CrossPlatformInputManager.GetAxisRaw("VerticalLook") * YSensitivity;
yRotation -= yRot * 10 * Time.deltaTime;
yRotation = yRotation % 360;
xRotation += xRot * 10 * Time.deltaTime;
xRotation = Mathf.Clamp(xRotation, MinimumX, MaximumX);
head.localEulerAngles = new Vector3(-xRotation, -0, 0);
character.localEulerAngles = new Vector3(0, -yRotation, 0);
}
// ----------------------------
}
}
我认为这可能会工作,但我得到一个错误。
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
private HeadLook m_HeadLook;
void Awake()
{
m_HeadLook = GetComponent<HeadLook>();
sensitivitySlider.value = m_HeadLook.MyHeadLook.XSensitivity;
}
我得到的错误是.. 的ArgumentException:GetComponent要求被请求的组件从MonoBehaviour或组件“HeadLook”起源或接口。
谢谢。
私人HeadLook m_HeadLook;
void Awake()
{
m_HeadLook = new HeadLook(8f,8f);
sensitivitySlider.value = m_HeadLook.MyHeadLook.XSensitivity;
}
您不能使用GetComponent,因为它不是MonoBehaviour。
另外,您的HeadLook似乎在创建一个并非真正需要的HeadLook对象。你似乎试图做一个单身人士,这将更像︰
public static HeadLook MyHeadLook = null;
public HeadLook (float rotX, float rotY)
{
if(MyHeadLook != null) {return;}
MyHeadLook = this;
rotX = XSensitivity;
rotY = YSensitivity;
}
这是真的简化,但它将是一个单身人士的开始。
编辑:有人在评论部分使它的使命,以确保您正确使用单身。我的回答只是提示你做错了事,我提供了一些简单的事情让你走。 所以这是一个链接到一个页面,完全解释它。
你只需从monobehaviour派生类:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[Serializable]
public class HeadLook : MonoBehaviour
{
...
你应该从需要时从MB派生。也许是在这种情况下,但通常情况下,如果不需要检查器分配或引擎的任何回调(更新,UI事件...),最好避免MB,因为它会增加内存使用量。 – Everts
错误说的那样: “GetComponent要求被请求的组件 'HeadLook' 导出从MonoBehaviour”
潜在的修正:
- 派生从MonoBehavior HeadLook和不为HeadLook定义构造函数(您应该通过其他方式设置rotX和rotY)
- 将HeadLook设置为你的调用脚本,在这种情况下你不会使用GetComponent(即m_HeadLook = new HeadLook(1f,2f))
该类不是从'MonoBehaviour'派生的,因此不能得到它的组件,因为它不是组件。尝试找到包含“HeadLook”实例的脚本。 –
错误所在的行是。 m_HeadLook = GetComponent (); –