- Home /
How to reference public floats to different scripts in different scenes?
I'm trying to link these scripts to change the difficulty of the game by adding force to a cube. Any help is appreciated.
Script 1:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody Rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
public float Speed = 50f;
void Start()
{
forwardForce = GetComponent<DifficultySelector>().Forwardforce;
}
// Update is called once per frame
void FixedUpdate()
{
Rb.AddForce(0, 0, forwardForce * Speed * Time.deltaTime);
if (Input.GetKey("d"))
{
Rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
Rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
if (Rb.velocity.magnitude > Speed)
{
Rb.velocity = Rb.velocity.normalized * Speed;
}
}
}
Script 2:
using UnityEngine; using UnityEngine.SceneManagement;
public class DifficultySelector : MonoBehaviour { public float Forwardforce = 50f;
public void Easy()
{
Forwardforce = 25f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
public void Normal()
{
Forwardforce = 50f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
public void Hard()
{
Forwardforce = 75f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Sorry I have no idea, what you're problem is, or what you're trying to do with that code...
Did you get this question in an email? Check your settings because Unity's site may have automatically tagged you as an expert on something, I myself was once automatically tagged as a 2D expert.
Answer by Magso · Jul 01, 2020 at 03:06 PM
forwardForce = GetComponent<DifficultySelector>().Forwardforce;
should work unless the DifficultySelector is on another GameObject, in that case you have to reference it.
GameObject difficulty;
difficulty = GameObject.Find("GameObject name");
forwardForce = difficulty.GetComponent<DifficultySelector>().Forwardforce;
Thanks for trying. It didn't work. I got this error: NullReferenceException: Object reference not set to an instance of an object Player$$anonymous$$ovement.Start () (at Assets/Scripts/Level Scripts/Player$$anonymous$$ovement.cs:19) The game object is on a separate scene so I don't think referencing it will work. I had a feeling saving the variable then finding the script and taking that variable would work but it obviously didn't or else I wouldn't be here right now.
Answer by RossGamer · Jul 03, 2020 at 07:40 AM
I'm just removing the difficulty altogether because it doesn't fit my game well anyway.
Your answer
![](https://koobas.hobune.stream/wayback/20220613002212im_/https://answers.unity.com/themes/thub/images/avi.jpg)