尝试从一个脚本中获取一个变量并应用于另一个脚本

时间:2019-06-23 23:02:47

标签: c# unity3d

我正在尝试使用UI滑块通过GetComponent功能更改播放器角色的移动速度。除了将我从滑块的移动创建的数字(浮动)应用于控制播放器移动速度的变量之外,我可以进行所有工作。

我用过Debug.Log();确定我要从一个脚本中获取的变量与另一个脚本不相等。似乎它们被存储为两个单独的变量。

当我移动滑块时,varspeed变量会跟踪数字。

在脚本BallScript中:

GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
Debug.Log(speedvar1);

在脚本PointBuyScript中:

public void Start()
{
    mySpeed.onValueChanged.AddListener(delegate { ValueChangeCheck(); });
}

public void LateUpdate()
{
    varspeed = mySpeed.value;
    Debug.Log(varspeed);
}

当我移动滑块时,来自PointBuyScript的控制台中的数字将随滑块缩放。但是,BallScript中的那个永远不变。

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()
    {




    }





}

1 个答案:

答案 0 :(得分:1)

此代码:

GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;

说“获取speedvar1中的值并将其分配给 PointBuyScript#varspeed。”也就是说,PointBuyScript#varspeed的值被更改(speedvar1保持不变)。

您可能想要:

speedvar1 = GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed;