C# 试图从一个脚本中获取变量并应用于另一个脚本
我正在尝试使用UI滑块来使用GetComponent功能更改我的玩家角色的移动速度。除了将我从滑块的移动中创建的numberfloat应用到控制播放器移动速度的变量之外,其他一切都正常工作 我使用了Debug.Log;确定我试图从一个脚本获取的变量不等于另一个脚本。似乎它们被存储为两个独立的变量 当我移动滑块时,varspeed变量跟踪数字 在脚本中:C# 试图从一个脚本中获取变量并应用于另一个脚本,c#,unity3d,C#,Unity3d,我正在尝试使用UI滑块来使用GetComponent功能更改我的玩家角色的移动速度。除了将我从滑块的移动中创建的numberfloat应用到控制播放器移动速度的变量之外,其他一切都正常工作 我使用了Debug.Log;确定我试图从一个脚本获取的变量不等于另一个脚本。似乎它们被存储为两个独立的变量 当我移动滑块时,varspeed变量跟踪数字 在脚本中: GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed
GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
Debug.Log(speedvar1);
当我移动滑块时,控制台中PointBuyScript的数字将随滑块缩放。然而,来自BallScript的一个永远保持不变
脚本代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallScript : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
private Rigidbody rb;
public float speedvar1;
public float SpeedMain;
void Start()
{
rb = GetComponent<Rigidbody>();
speedvar1 = GameObject.Find("Canvas").GetComponent<PointBuyScript>().mySpeed.value;
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.00f, moveVertical);
speed = speedvar1; // this is where I try and update the speed variable to the slider number
rb.AddForce(movement * speed);
}
void LateUpdate()
{
Debug.Log(speedvar1);
Debug.Log(speed);
// Debug.Log(SpeedMain);
}
}
PointBuyScript代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PointBuyScript : MonoBehaviour
{
public Slider mySpeed;
public float varspeed;
public float mainSpeed;
public void Start()
{
// GameObject speed1 = GameObject.Find("Ball");
// BallScript hellome = speed1.GetComponent<BallScript>();
// varspeed = GameObject.Find("Ball").GetComponent<BallScript>().speed;
//Adds a listener to the main slider and invokes a method when the value changes.
mySpeed.onValueChanged.AddListener(delegate { ValueChangeCheck(); });
}
public void Update()
{
// Debug.Log(mySpeed.value);
//mainSpeed = mySpeed.value;
}
public void LateUpdate()
{
varspeed = mySpeed.value;
Debug.Log(varspeed);
}
// Invoked when the value of the slider changes.
public void ValueChangeCheck()
{
}
}
此代码:
GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
谢谢你的帮助,但我仍然有同样的问题。当你移动滑块时,varspeed真的改变了吗?在ball脚本中,你认为你在哪里获得了速度变化?第一个代码块在哪里被调用?我认为如果我从另一个脚本中更改了速度值,它将通过所有脚本自动更新变量。如果不是这样的话,那可能就是我有这个问题的原因。
GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
speedvar1 = GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed;