29

In Unity, I want one object to have a falling speed variable that all the other objects can access. For various reasons, I can't use the inbuilt gravity for what I'm trying to do.

How can I access a variable in one object repeatedly, so that when it updates I get the updated variable, from another object?

Dakeyras
  • 1,829
  • 5
  • 26
  • 33

4 Answers4

31

There are several ways to achieve this.

If you want the speed variable controlled by a component which is attached to a GameObject MyObject

public class SpeedController : MonoBehaviour
    public float speed;
    // maybe you want restrict this to have read access, then you should use a property instead

In other classes you can do:

GameObject go = GameObject.Find ("MyObject");
SpeedController speedController = go.GetComponent <SpeedController> ();
float courrentSpeed = speedController.speed;

Take care that there is one object named MyObject only otherwise things get messed up.

Alternatively you can define a SpeedController member in every class that needs access to speed and set a reference via drag and drop in Unity editor. You save the lookup then but of course this is pretty inconvenient if needed in many classes.


Another way is to create a singleton which holds the speed variable and have:

public class MyGlobalSpeedController {
    private static MyGlobalSpeedController instance = null;
    public static MyGlobalSpeedController SharedInstance {
        get {
            if (instance == null) {
                instance = new MyGlobalSpeedController ();
            }
            return instance;
        }
    }
    public float speed;
}   

So all classes can access this:

float currentSpeed = MyGlobalSpeedController.SharedInstance.speed

As Jan Dvorak stated in comments section:

public class SpeedController : MonoBehaviour
    public static float speed;

[Update] Thanks to Jerdak. Yes Component.SendMessage should be definitely on the list:

go.SendMessage("GetFallingSpeed");

Again you need to have a reference to go like described in the first solution.

There are even more solutions to this problem. If you are thinking of game objects that are active in all scenes, you should have a look at Unity singleton manager classes

JoshuaCF
  • 49
  • 9
Kay
  • 12,918
  • 4
  • 55
  • 77
  • 3
    Don't forget [SendMessage](http://docs.unity3d.com/Documentation/ScriptReference/Component.SendMessage.html) It's def. not the best option but it's useful on occasion. – Jerdak Dec 15 '12 at 14:12
  • I keep getting this error: 'error CS0236: A field initializer cannot reference the nonstatic field, method, or property' (I am using your first method) – Dakeyras Dec 15 '12 at 21:05
  • Here: SpeedController speedController = go.GetComponent(); – Dakeyras Dec 17 '12 at 17:17
  • @Dakeyras Seems like you are doing it in initialisation of a member variable. Maybe [A realy easy c# question](http://answers.unity3d.com/questions/186981/a-realy-easy-c-question.html) sheds some light on it. – Kay Dec 17 '12 at 19:45
  • The part with the property is wrong. The property is static while the field is not so it cannot return it since it cannot access it. – Everts Mar 13 '14 at 16:40
  • It's a [Singleton Pattern](https://en.wikipedia.org/wiki/Singleton_pattern). `MyGlobalSpeedController.SharedInstance` returns an instance and `speed` is the field of this instance. – Kay Mar 13 '14 at 16:49
  • go.SendMessage("GetFallingSpeed"); how could this works? send message doesn't have return value – Kevin Tanudjaja Dec 11 '19 at 06:34
5

If I were you I would just make this speed variable "static public" so you can access it from anywhere. You should always avoid "find.anything" etc functions, they are quite slow. There is no reason for you to look for something that you exactly know where it is.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
Furjoza
  • 65
  • 1
  • 4
2

if it is in the fixedUpdate – Martin j

seems like it works well in Awake too. Both scripts are added to the same GameObject.

public class FirstScript : MonoBehaviour {
    protected internal GameObject myobject;
private void Awake() {
       myobject = (GameObject)Instantiate(Resources.Load("nameofprefab"));
       myobject.transform.parent = gameObject.transform;
...
public class SecondScript : MonoBehaviour {
    private GameObject myobject;
private void Awake() {
       myobject = gameObject.GetComponent<FirstScript>().myobject;
       myobject.SetActive(false); //for example
...       
NBAH79
  • 21
  • 4
0
other.GetComponent<class name>().object name;
Martin j
  • 511
  • 1
  • 9
  • 31