Home > Blockchain >  How can I access a variable from another script in Unity?
How can I access a variable from another script in Unity?

Time:06-05

I want to be able to use a variable from one script in another script. My goal is to allow me to reference the particleScale variable and use it to affect the size of the object connected to the second script. I also ant to later reference other variables from other scripts. There also will be several instances of each object. This is my first script;

public class Particle : MonoBehaviour
{
    
    public float particleSize;
    public Transform particle;

    void Start()
    {
        particle.localScale *= particleSize;
    }
}

This is my second;

public class Magnetic : MonoBehaviour
{
    
    public Transform magnetic;

    void Start()
    {
        magnetic.localscale *= Particle.particleSize;
    }
}

Help!

CodePudding user response:

there are few ways to do it,

  1. Using the FindObjectOfType()
public class Magnetic : MonoBehaviour
{
    public Transform magnetic;
    Particle particle

    void Start()
    {
        particle = FindObjectOfType<Particle>();
        magnetic.localscale *= particle.particleSize;
    }
}
  1. Using a singleton pattern (only if you are just going to have a single object of type Particle)
public class Particle : MonoBehaviour
{
    public static Particle Instance;
    public float particleSize;
    public Transform particle;

    void Awake() {
        if (Instance != null) {
          Destroy(gameObject);
        } else {
          Instance = this;
        }
    }
    void Start()
    {
        particle.localScale *= particleSize;
    }
}

then the class will globally accessible from Particle.Instance so you can use any public methods from it or in your case the Particle.Instance.particleSize

CodePudding user response:

Try this:

public class Particle : MonoBehaviour
{
    public static Particle instance;
    public float particleSize;
    public Transform particle;

    void Awake()
    {
      instance = this;
    }
    void Start()
    {
        particle.localScale *= particleSize;
    }
}


public class Magnetic : MonoBehaviour
{
    
    public Transform magnetic;

    void Start()
    {
        magnetic.localscale *= Particle.instance.particleSize;
    }
}
  • Related