Home > Software design >  How to access an object in a script from another script
How to access an object in a script from another script

Time:04-05

I have 3 scripts here the first is Weapon the 2nd one where i created some objects of Weapon and the 3rd where i want to use the method Setid() from the first script to change the id of an object in the 2nd script:

1st script(not attached to any object)

public class Weapon : MonoBehaviour
{
    private int id;
    public Weapon(int id)
    {
        this.id = id;
        
    }
    public int Getid() { return id; }
    public void Setid(int id) { this.id = id; }
}

2nd script : attached an object under the parent player

public class GunController : MonoBehaviour
{   
    Dictionary<int, Weapon> Loadout= new Dictionary<int, Weapon>();

    Weapon STG44 = new Weapon(0);
    Weapon AK74 = new Weapon(1);
    Weapon AA12 = new Weapon(2);
    Weapon MiniGun = new Weapon(3);
private void Start()
    {
        Loadout.Add(0, STG44);
        Loadout.Add(1, AK74);
        Loadout.Add(2, AA12);
        Loadout.Add(3, MiniGun);
       ;


    }
}

3rd script attached to a different object but same parent:

    public class PickUpWeapon : MonoBehaviour
    {
        public GameObject PressE;
        public bool Triggered;
        private void Start()
        {
            PressE.SetActive(false);
        }
        void OnTriggerEnter(Collider collision)
        {
            if(collision.CompareTag("Box"))
            {
                PressE.SetActive(true);
                Triggered = true;
            }
        }
        void OnTriggerExit(Collider collision)
        {
            PressE.SetActive(false);
            Triggered = false;
        }
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.E) && Triggered)
            {
                Debug.Log("s");
//need to call Setid(5) here for the object AK74 from the 2nd script
            }
        }

CodePudding user response:

To do this, simply have a reference to the 2nd script in your 3rd, like e.g. so:

GunController myRef = theObjectThatThe2ndScriptIsSittingOn.getComponent<GunController>();

Then with myRef you can acces anything that is public in this script,

FOR THIS, THE VARIABLE THAT YOU ARE CALLING/ACCESING NEEDS TO BE PUBLIC

myRef.AK47.setId(5);
//OR
myRef.Loadout[1].setId(5);

Also: Unless you need the Inheritance from the MonoBehaviour in the 1. Script I would remove it.

CodePudding user response:

Maybe this can help you to understand how static script in Unity works: link01 link02

  • Related