Access variables/functions from another Component

前端 未结 3 624
攒了一身酷
攒了一身酷 2020-11-22 11:44

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

  • 1x Player
  • 1x Enemy

Each with their own scri

相关标签:
3条回答
  • 2020-11-22 12:01

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 12:02

    No since Health is not part of the collision object, but Enemy_Stats. You can cache a Component (that's what Enemy_Stats is) if you use it multiple times to save you some typing (and some performance, but that is rather marginal for this example). Also you can cache "known" components like in this case Player_Stats. You can do this e.g. in Start or with a public variable and the inspector.

    What you should probably do though is to make the enemy be responsible for his life and not the player, so move the Destroy-part to Enemy_Stats (into the Health property to be exact).

    0 讨论(0)
  • 2020-11-22 12:09

    The first thing to make this shorter (and eventually faster) would be to store this: gameObject.GetComponent<Character_Stats>() on Start() in a private variable (you should avoid calling GetComponent on a frequent basis if you can avoid it).

    For the Health variable, a way of avoiding GetComponent calls could be caching: you create a Dictionary<GameObject, Enemy_Stats> and read from that as soon as this gameobject collided once

    0 讨论(0)
提交回复
热议问题