Hossein Rashno
Hossein Rashno

Reputation: 3469

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.

That variable may change five time's in all the game duration so I did not want look for change every frame, Just when it changed, Something magically tell that script's too update the value!

I have some idea to solve this problem but I think these are not good:

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;
}

And in this project those other script's need the value of "Speed" in any frame, Not just in some situation

Upvotes: 1

Views: 2417

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

Do not have multiple speed variables, just have one, and call for it every time you need to get it

SpeedHolder speedHolder;

public void Update()
{
    transform.position += speedHolder.Speed * Time.deltaTime;
}

If you REALLY want this done another way... you can use events and delegates.

public class SpeedHolder
{
    private float _speed;

    public event Action<float> OnSpeedChange;

    public float Speed
    {
        get { return _speed; }
        set { SetSpeed(value); }
    }

    public SetSpeed(float value)
    {
        _speed = value;
        if(OnSpeedChange != null)
            OnSpeedChange(_speed);
    }
}

now in every start method of every script which uses a speed float variable, you need to add this line: SpeedHolder.OnSpeedChange += ChangeSpeed; and have a method like this one:

public void ChangeSpeed(value)
{
    speed = value;
}

Upvotes: 4

Related Questions