0

I have 2 c# scripts in my game. On of them is in my "main player object" and the other script is in "my main camera". I want to declare a float variable in the script of my main player, and in every game second i want to record the x position of my player in that variable and at the same time passing this value to the my main camera's script and assigning this value into the x position of my main camera in every game second. How can I pass a variable to a script from another one ? Or how can i create a variable which can be used by any script in my game ?

semiramis
  • 19
  • 8
  • There are a few ways to handle this. One is to make a public Transform/GameObject variable on the camera script, and drag the player object onto it in the Unity inspector. Then, you can use it to access the `transform.position.x` of the player. That's the simplest solution for your case, no extra scripting needed on the player script itself. However, this would only make this variable accessible to the camera script - if you need it accessible from all scripts in your project you'll need to approach this differently. – Serlite May 16 '16 at 13:56
  • 1
    Do what Tom says. This question has been asked 1000 times! – Fattie May 16 '16 at 13:57

1 Answers1

2

There's an answer here that explains this problem in great detail, but the simplest way that is included in that answer would be to do something like the following:

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

And then in other scripts:

GameObject gameObject = GameObject.Find ("Some object");
Speed theSpeed = gameObject.GetComponent <Speed> ();
float mySpeed= theSpeed.speed;
Community
  • 1
  • 1
Tom
  • 2,372
  • 4
  • 25
  • 45