Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading