- Home /
Best way to get variable from another script
I'm working on a 2D game and I have many c# script. Some variable like Speed
influence to a lot of gameObject's and script. I want to all of these script's read Speed
variable from just one script and I do this with property and it worked very well.
But my problem is I want when I change the Speed
from that script, Other script detect this change and change their own Speed
variable. Currently it's not like this because those script read Speed
in Start()
method. I have some idea to solve this problem but I think these are not good:
Get variable from that component in
Update()
orFixedUpdate()
method (I think it's bad because every frame this code runs)In that public script I create a list of script's that use
Speed
variable and whenSpeed
changed, send a message to those script's.And I have a lot of other idea that I know it's wrong so I don't write that.
Update:
This is my public class that contain Speed
variable:
using UnityEngine;
using System.Collections;
public class Utility : MonoBehaviour {
public float _Speed = 2f;
public float Speed
{
get{return _Speed;}
set{_Speed = value;}
}
void Start () {
}
void Update () {
//Here I can detect change of this variable and send message to other scripts
}
}
And other script access to that variable like this( Just example):
void Start () {
float mySpeed = GetComponent<Utility> ().Speed;
}
void Update () {
// Or here I can read speed every frame like below:
// mySpeed = GetComponent<Utility> ().Speed;
}
Answer by tanoshimi · Jun 11, 2015 at 10:19 PM
Cache a reference to the utility component, not to the Speed member. I.e.
Utility utility;
void Start () {
utility = GetComponent<Utility> ();
}
void Update () {
// Do stuff with utility.Speed;
}
Your answer
Follow this Question
Related Questions
public class variable in inspector like other components? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers