Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

c# - Access variables/functions from another Component

So im trying to change a variable in another script by touching a cube. Current setup

  • 1x Player
  • 1x Enemy

Each with their own script Enemy_Stats & Character_Stats
As you can see in this little snippet it's quite a workaround to access the variable from another script.

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Enemy")
    {
        collision.gameObject.GetComponent<Enemy_Stats>().Health = 
            collision.gameObject.GetComponent<Enemy_Stats>().Health 
            - gameObject.GetComponent<Character_Stats>().AttackDamage;

        if (collision.gameObject.GetComponent<Enemy_Stats>().Health <= 0)
        {
            Destroy(collision.gameObject);
        }
    }
}

Iam new to Unity, but isn't there a way to just refer it with something like:
collision.Health?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to access variables/functions from another Class. The variable or function you want to access or called must be public not private.

public class ScriptA : MonoBehaviour{

    public int playerScore = 0;

    void Start()
    {

    }

    public void doSomething()
    {

    }
}

Access variable playerScore in ScriptA from ScriptB. First, find the GameObject that the script or component is attached to with the GameObject.Find function then use the GetComponent function to retrieve that script or component that is attached to it.

public class ScriptB : MonoBehaviour{

    ScriptA scriptInstance = null;  

    void Start()
    {
      GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
      scriptInstance = tempObj.GetComponent<ScriptA>();

      //Access playerScore variable from ScriptA
      scriptInstance.playerScore = 5;

     //Call doSomething() function from ScriptA
      scriptInstance.doSomething();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...