Lukas
Lukas

Reputation: 437

Transfer of float of Input Field to a new Scene and new Script in Unity and C#

I have a car game, you define in one scene all settings, like the speed, after that you can press play, the new scene shows up.

The code of the first Scene is this, it is attached to an empty GameObject:

using UnityEngine;
using UnityEngine.UI;

public class Data : MonoBehaviour {

      static public float speed=10f;

      public InputField speedField;

      void Update()
      {
         speed = float.Parse(speedField.text);
         Debug.Log(speed);
      }
}

In the next scene I have to work with speed in a script called Driving, which is attached to the cars. And I have to destroy the Data-Script, because in the next scene I don't have an Input-Field. How can I access to speed?

I tried a couple of hours and I'm not able to find a solution for this easy question. Thanks.

Upvotes: 0

Views: 294

Answers (1)

paul p
paul p

Reputation: 450

There are many ways you can solve this problem what I will suggest is to use the static script for holding data only, but you cant assign it to game object. It is a simple approach as you don't need to use a singleton.

public static class Data{
private static int speed
public static int speed{
    get 
    {
        return speed;
    }
    set 
    {
        speed = value;
    }
}

If you want to assign your script to game object then use DontDestroyOnLoad(gameObject); Or use playerprefs to save data.

Upvotes: 3

Related Questions