不知道如何从另一个脚本(不同的游戏对象)访问脚本的变量



所以,我目前正在使用一个小型快速拨号。我在表盘上附加了一个脚本,等待速度测量,然后将其转换为适当的角度并显示。现在我想从平面上获得速度测量,并将其提供给表盘。但是我想不通。这是拨号代码:

static float minAngle = 70.64f;
static float maxAngle = -269.69f;
static RotateSpeedDial thisSpeedo;
void Start () {
thisSpeedo = this;
}
public static void ShowSpeed(float speed, float min, float max) {
float ang = Mathf.Lerp(minAngle, maxAngle, Mathf.InverseLerp(min, max, speed));
thisSpeedo.transform.eulerAngles = new Vector3(0,0,ang);
}

这是飞机代码中给出速度的部分:

public Rigidbody rb;
public GameObject ScriptHolder = GameObject.Find("SpeedDial");
public RotateSpeedDial = ScriptHolder.GetComponent<RotateSpeedDial>();
public void Update()
{
rb = this.GetComponent<Rigidbody>();
RotateSpeedDial.ShowSpeed(rb.velocity.magnitude,0,100);
}

RotateSpeedDial.ShowSpeedstatic,因此根本不需要通过GetComponent获取对它的引用。

像一样简单使用

// Reference this via the Inspector and you don't need GetComponent at all
public Rigidbody rb;
// As a fallback get it ONCE on runtime
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody>();
}
public void Update()
{
RotateSpeedDial.ShowSpeed(rb.velocity.magnitude, 0, 100);
}

然而,这里有一种辛格尔顿模式,这是非常有争议的。。。您应该通过Inspector来引用它。

FindGetComponent都不能用于类中的字段定义。此外,ScriptHolder不能用于初始化类中的字段,因为它是在运行时本身分配的,而不是静态值。你需要一些方法来解决它,比如AwakeStart

因此,您会有例如

// Reference all these via the Inspector using drag&drop
public Rigidbody rb;
// If you drag this in via the Inspector you wouldn't need the "ScriptHolder"
// at all.
public RotateSpeedDial rotateSpeedDial;
public GameObject ScriptHolder;
// Or as a fallback get them all on runtime ONCE like
// I use a little rule of thub: Get and initialize your own stuff at Awake
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody>();
}
// Get other objects stuff on Start 
// This way you can almost always be sure that the other stuff 
// is already initialized when you access it
private void Start()
{
if(!rotateSpeedDial)
{
if(! ScriptHolder) ScriptHolder = GameObject.Find("SpeedDial");
rotateSpeedDial = ScriptHolder.GetComponent<RotateSpeedDial>();
}
// Or simply use
if(!rotateSpeedDial) rotateSpeedDial = FindObjectOfType<RotateSpeedDial>();
}
public void Update()
{
rotateSpeedDial.ShowSpeed(rb.velocity.magnitude, 0, 100);
}

然后你就不会在RotateSpeedDial:中使用任何static

float minAngle = 70.64f;
float maxAngle = -269.69f;
public void ShowSpeed(float speed, float min, float max) 
{
var ang = Mathf.Lerp(minAngle, maxAngle, Mathf.InverseLerp(min, max, speed));
transform.eulerAngles = Vector3.forward * ang;
}

最新更新