- Home /
how to pass dynamic value from one script to other script ?
the situation:
I have one script named GameController .In this script,i want to record the mouse delta position when putdown jump button.the code show as following:
public class GameController : MonoBehaviour
{
private Vector3 lastPos;
public Vector3 deltaPos;
private Boolean duringStop = false;
private Boolean trackMouse = false;
void Update ()
{
if(Input.GetButtonUp("Jump"))
{
Time.timeScale = Time.timeScale==1.0f ? 0.0f : 1.0f;
duringStop = Time.timeScale == 1.0f ? false : true;
}
if (duringStop)
{
if (Input.GetMouseButtonDown(0))
{
trackMouse = true;
lastPos = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
trackMouse = false;
deltaPos = Input.mousePosition - lastPos;
Debug.Log(deltaPos);
}
}
}
}
then after putdown jump button again,the game will continue.But i want that vale deltaPos
can be passed to another script that control player movement.the player will add a force from the value,and change the velocity.
so how to pass value that when the deltaPos
changes? because it can be changed after every time jump button has been putdown,so I don't know how to notify another script that the value has been changed. whats more,the value will be used in fixedupdate funtion.
Answer by lathster · Feb 07, 2017 at 01:45 PM
If there is only going to be one of these scripts in you entire game (i.e The GameController script is only one one object and that object is the only instance of that object in the game) you can create an instance of this script. To do that add:
public static GameController GCInstance;
To where you declare your other variables. Then use any of the Start(), Awake() or OnEnable() methods built into unity to set GCInstance to this. For Example:
void Awake(){
GCInstance = this;
}
You can then call the deltaPos in an Update() or FixedUpdate() method in the other script using:
GameController.GCInstance.deltaPos
For example:
void Update(){
someVector3 = GameController.GCInstance.deltaPos;
}
Or
void Update(){
SomeMethod(GameController.GCInstance.deltaPos);
}
Hope this helps :)
Answer by Chikari · Feb 06, 2017 at 05:30 PM
1, Put both scripts GameController and OtherScript on the same GameObject.
2, In OtherScript, add the function otherFunction that needs your deltaPos. Make it public.
3, In GameController, call GetComponent<OtherScript>().otherFunction(deltapos);
Your answer
![](https://koobas.hobune.stream/wayback/20220612110442im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Object reference is NULL when IT IS set to an instance of an object? 1 Answer
Most efficient way to remove a null object from a dictionary 3 Answers
A real head-scratcher 0 Answers