A variable that can be used in 2 scripts?

Let’s say I want to use

public int variable = 1;

as a variable. A keycode sets it to 2.

Then, in another script:

if (variable == 2)
{
     something;
}

How can I use a variable in 2 scripts?

EDIT 1/4-17: It was with this thread that I realized that I’m never going to be able to make a game I’m satisfied with.

GetComponent() will grab reference to a other script object so you can access its public vars

1 Like
GetComponent<press_start>();

It doesn’t work.

press_start.cs:

using UnityEngine;
using System.Collections;

public class press_start : MonoBehaviour {
    //Sound
    public AudioClip startup;
    private AudioSource source;
    public AudioClip titleScreenMusic;
    private AudioSource source2;
    //Other
    public Sprite regular;
    private SpriteRenderer sprite_renderer;
    public int press_enter = 0;
    //Time
    public float timeRemaining = 5;
    public int loadHouseLevel = 0;

    // Use this for initialization
    void Start () {
        //press start graphic
        GetComponent<SpriteRenderer>().sprite = regular;
        sprite_renderer = GetComponent<SpriteRenderer> ();
        //sound (startup)
        source = GetComponent<AudioSource>();
        source2 = GetComponent<AudioSource>();
        source2.PlayOneShot(titleScreenMusic, 1F);
      
    }
  
    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown (KeyCode.Return) && press_enter == 0)
        {
            press_enter = 1;
            sprite_renderer.enabled = false;
            source.PlayOneShot(startup, 1F);
        }

        if (press_enter == 1)
        {
            timeRemaining -= Time.deltaTime;
        }

        if (timeRemaining < 0)
        {
            Application.LoadLevel("path");
            loadHouseLevel = 1;
        }

    }
  
}

cutscene.cs:

using UnityEngine;
using System.Collections;
public class cutscene : MonoBehaviour {
    public Sprite home;
    public Sprite inTheMailbox;
    private SpriteRenderer sprite_renderer;

    public float timeRemaining2 = 4;



    // Use this for initialization
    void Start () {
        GetComponent<SpriteRenderer>().sprite = home;
        sprite_renderer = GetComponent<SpriteRenderer>();

        GetComponent<press_start>();
    }
  
    // Update is called once per frame
    void Update () {
        if (loadHouseLevel == 1)
        {
            loadHouseLevel = 2;
        }

        if (loadHouseLevel == 2)
        {
            timeRemaining2 -= Time.deltaTime;
        }

        if (timeRemaining2 > 0)
        {
            GetComponent<SpriteRenderer>().sprite = inTheMailbox;
        }
    }
}

You need to declare a variable for it first. Basically do it the exact same way you are doing your SpriteRenderer setup.

public press_start variableName; for instance.

Note that GetComponent is going to assume your scripts are on the same game object.

This may help. It explains conceptually some of the common ways to communicate between scripts.

3 Likes

Can you be more specific? Can you put the

code I need to type

inside a code tag?

Follow BoredMormon’s link. Script-to-script communication is one of the basic skills necessary for Unity, and we’d honestly be doing you a disservice by just providing the line of code you need.

I’ve watched the video. I still don’t know what to do.

A good way to initiate yourself to a particular programming technic is to isolate it.

Make a new project with only 2 scripts corresponding to the core of your problem, keep it as simple as it gets. Then do trials and errors until you’ve figured it out and are comfortable with it !

How am I supposed to do that? I’m not the guy that figures something out.

I took your advice.

script1:

using UnityEngine;
using System.Collections;

public class script1 : MonoBehaviour {

    public int var1 = 0;

    // Use this for initialization
    void Start () {
      
    }
  
    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            var1 = 1;
        }
    }
}

script2:

using UnityEngine;
using System.Collections;

public class script2 : MonoBehaviour {

    public int var2 = 0;

    // Use this for initialization
    void Start () {
        GetComponent<script1>(var1);
    }
  
    // Update is called once per frame
    void Update () {
        if (var1 == 1)
        {
            var2 = 1;
        }
    }
}

Not working.

That’s because you’re doing it wrong. Although it was mentioned in BoredMormon’s video, you can look here. Unity Script Reference – Overview: Accessing Other Game Objects

OK, now that I’ve actually watched that video, it’s not nearly as helpful as I thought it’d be.

This is better, with code samples. Make sure you switch the language to C#, though!

It’s good that you started it, now you also need to learn to read compiler errors.

Unity is probably telling you that it doesn’t know the identifiers lines 10 and 15 in your script2. Following the previously shared link should point you in the right direction to fix it !

…I just can’t do it.

script2:

using UnityEngine;
using System.Collections;

public class script2 : MonoBehaviour {

    public int var2 = 0;

    // Use this for initialization
    void Start () {
       

    }
   
    // Update is called once per frame
    void Update () {
        if (var1 == 1)
        {
            var2 = 1;
        }
        script1 otherScript = GetComponent<script1>();
        otherScript.var1();
    }
}

Oh okay then… here’s an example which you can edit to suit your needs.

ReadMore nextTime = GetComponent<ReadMore>();
nextTime.something=1;

If you want to call a function you would do

nextTime.SomeFunction();

If it helps, you’re getting closer to the right answer. I’m still not going to hand it to you, but let me see if I can give you some pointers in the right direction:

  1. What you’re ultimately wanting to do is to modify & access var1 on script1 from script2 - var2 does not need to exist, and it’s only confusing the problem. Go ahead and delete that.

  2. Line 20 in the script you posted is exactly right.

  3. When you see someName(), the parentheses on the end mean that it’s a function. I’m guessing you copied that code from the samples on the docs page, which are referencing functions on other objects, whereas you are trying to reference a variable on another object. If var1 were a function, you’d have that line correct! Since var1 is not a function, though, that’s not how you access it. You can set var1 almost like you are (currently) setting var2, you just need to add the otherScript part to that line.

Finally, as @_met44 says, learn to use error messages. If you don’t know how to see them, look at the very bottom of the Unity window - you can click on this part to open the console and see more information, too. (With your script as it is in your last comment, it will definitely be giving you at least one error, on line 16.) If you double-click on the error in the console, it’ll open the script to the line containing the error, and as you get better, you’ll learn what the error messages mean. And even if you don’t know what they mean, definitely include them when asking for help - they help us find your problems!

using UnityEngine;
using System.Collections;

public class script2 : MonoBehaviour {

    public int var2 = 0;
    ReadMore var1 = GetComponent<script1>();
    var1.something = 1;

    // Use this for initialization
    void Start () {
      

    }
  
    // Update is called once per frame
    void Update () {
        if (var1 == 1)
        {
            var2 = 1;
        }
      
    }
}

I still can’t get it to work.

I don’t know what “ReadMore” should be replaced with, what “nextTime” should be replaced with, and what “ReadMore” inside ‘<’ these ‘>’ should be replaced with, I don’t know what “something” should be.

And I’m getting an error, line 8, “Unexpected symbol ‘=’ in class, struct or interface member declaration”.

Go back to what your script was in the previous comment, it was pretty close to right in that one. Then follow my comment from there.

What, like this?

public int otherScript var1;