简体   繁体   中英

How do I pass a variable between scripts in Unity 2d C#

For example, I have a variable "Wisps" that I want to change when the player picks up an object. But I don't know how to do it. I tried to add a WispDisplay object to call the classes, like in Java, but it doesn't seem to work.


public class WispCode : MonoBehaviour
{
    WispDisplay wd = new WispDisplay();
    
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
          wd.setWisp(wd.getWisp()+1);
            Destroy(gameObject);
        }
    }
}

public class WispDisplay : MonoBehaviour
{
    public int Wisp  = 5;
    public Text WispText;
    void Start()
    {

    }

    void Update()
    {
        WispText.text = "Wisp: " + Wisp.ToString();
    }
    
    public int getWisp()
    {
        return Wisp;
    }
    public void setWisp(int newWisp)
    {
        Wisp = newWisp;
    }
    
}

Easiest (a tiny bit dirty) way is to use a static variable. Downside: you can only have exactly ONE.

Example:

public class MyClass: MonoBehaviour {
    public static int wisps;
}

Then, in ANY class, just use this to access it:

MyClass.wisps = 1234;

The more elegant way, working with multiple class instances, is using references.

Example:

public class PlayerClass: MonoBehaviour {
    public int wisps = 0;
}

public class MyClass: MonoBehaviour {
    public PlayerClass player;

    void Update(){
        player.wisps += 1;
    }
}

Then, you need to drag-drop (aka "assign") the "PlayerClass" Component (attached to the player) to the the Gameobject that should increase the Wisps count. You can duplicate these objects after assigning the reference.

Now, if you actually want to have some sort of collectible, I'd suggest this approach:

You Have a Player "PlayerClass" and some Objects that are collectible, which have Trigger Colliders.

The objects have this code:

public class Example : MonoBehaviour
{   
    private void OnTriggerEnter(Collider other)
    {
        // probably a good idea to check for player tag:
        // other.compareTag("Player");
        // but you need to create the "Player" Tag and assign it to Player Collider Object. 
        if(TryGetComponent(out PlayerClass player))
        {
            player.wisps += 1;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM