0

I want that when the player have low health, a red screen (already did a loop animation for it) with an animation plays (it plays automatically that's why im just activating the gameObject),I tried to do it with saving the value in a text file and read it from the other script, but is not optimized and it doesn't work, what it looks like :

    public void CreateText()
    {
        string path = Application.dataPath + "/Datas/data";
        if (!File.Exists(path))
        {
            File.WriteAllText(path, "" + health);
        }
        else
        {
            File.Delete(path);
            File.WriteAllText(path, "" + health);
        }
    }

In the other Script :

    public int health = 1000;
    public string health0;
    public string path = Application.dataPath + "/Datas/data";
    public GameObject healthbar;

    void Update()
    {
        Int32.TryParse(health0, out health);
        File.ReadLines(path);
        if (health <= 600)
        {
            healthbar.SetActive(true);
        }
        else
        {
            if (healthbar.activeInHierarchy == true)
            {
                healthbar.SetActive(false);
            }
        }
    }
derHugo
  • 83,094
  • 9
  • 75
  • 115
Smoodie
  • 15
  • 6
  • You don't need a file for this, you need a reference to the other script. It's a bit hard to help clearly without seeing the rest of the code, can you post both scripts? – Cadmonkey33 Jan 26 '23 at 03:32
  • Cadmonkey33 I did what I wanted to do in the same actual script and is working, but I will search abt references tho, thx for your answer!! – Smoodie Jan 26 '23 at 08:10
  • 1
    Get a reference to your script and access its public field .. going through FileIO is damn expensive and completely overkill for basically any application out there ^^ – derHugo Jan 26 '23 at 08:21

1 Answers1

0

You can access scripts from other scripts just by getting the script component (like any other component). Lets say you have a game object A with an attached script ScriptA and also a game object B with a script ScriptB. To access ScriptB from ScriptA, you would need to:

class ScriptA : Monobehaviour {

    void Method() {
        GameObject b = GameObject.Find("B");  // get somehow a reference to B
        ScriptB scriptB = b.GetComponent<ScriptB>();  // get access to the script
        // now you can access all public stuff from the script
        scriptB.publicAttribute ...
        scriptB.publicMethod() ...
    }
}

For such runtime logic like you have with the healthbar, you should not use the filesystem. This is really an unnecessary detour.

taiyo
  • 535
  • 1
  • 7